to.period
的 xts 引用说:
“值得注意的是,默认情况下所有日期都将与每个期间的结束日期对齐”
在下面我希望看到输出显示 9/12 或 9/18 作为日期输出。但 显然我做的事情不对。那么“对齐”是什么意思,以及如何获得周界限?
x1 = xts(1.23, as.Date("2016-09-15"))
x1
[,1]
2016-09-15 1.23
to.period(x1, period="weeks", indexAt="firstof")
x1.Open x1.High x1.Low x1.Close
2016-09-15 1.23 1.23 1.23 1.23
to.period(x1, period="weeks", indexAt="lastof")
x1.Open x1.High x1.Low x1.Close
2016-09-15 00:00:00 1.23 1.23 1.23 1.23
但是
to.period(x1, period="months", indexAt="lastof")
x1.Open x1.High x1.Low x1.Close
2016-09-30 1.23 1.23 1.23 1.23
非常感谢。
我在 Windows 10 上使用 R 3.3.1
最佳答案
查看to.period()
的源代码,它调用firstof()
和lastof()
。它对月、年、季度和日有特殊处理,但对周没有特殊处理:
if (indexAt == "lastof") {
ix <- as.POSIXlt(c(.index(xx)), tz = indexTZ(xx))
if (period %in% c("years", "months", "quarters",
"days"))
index(xx) <- as.Date(lastof(ix$year + 1900, ix$mon +
1))
else index(xx) <- lastof(ix$year + 1900, ix$mon +
1, ix$mday, ix$hour, ix$min, ix$sec)
}
当您查看lastof(或firstof)的代码时,您会发现没有周处理,因为POSIX数据处理的工作方式(年,月,日,小时,分钟,秒 - 没有周的概念)。
看来endpoints()
(由to.period()
调用)是唯一进行特殊周处理的地方。
我认为你可以自行修改每周的向上/向下舍入。例如。如果日期采用 POSIXct 形式(自 1970 年以来的秒数),则除以 604800(7 天的秒数),调用 ceiling()
或 floor()
,然后乘以 604800。(呃,我认为您需要在末尾添加 259200(3 天内的第二个),因为 1970 年 1 月 1 日,POSIXct 时间的基础,是星期四而不是星期日。)
关于r - 在 xts::to.period() 中如何获取周边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39551719/