了解函数端点

Understanding function endpoints

我有一个 returns 的时间序列。在第一列中,我有我所有的日期。有了这个功能(搜索小时),我终于设法获得了每个月的第一个值。

问题是,第 1 天并不总是第一个值。有时是第 2、3、4、5 天等

幸运的是有了这个功能一切正常:

library(xts)
month<- data[,1] ## all my dates    
first.values <- month[head(endpoints(month, "months") + 1, -1)]

我想了解的是:为什么是 +1 和 -1?这就是我想了解的全部内容。

我对代码的工作不满意,我真的很想了解。不幸的是,我没有足够的声誉来联系或评论某人(因为我在这里找到了这段代码)。

让我们准备样本数据:

month <- seq.Date(from=Sys.Date()-5,to=Sys.Date()+10,by="day")

# [1] "2018-06-18" "2018-06-19" "2018-06-20" "2018-06-21" "2018-06-22" "2018-06-23" "2018-06-24" "2018-06-25" "2018-06-26"
# [10] "2018-06-27" "2018-06-28" "2018-06-29" "2018-06-30" "2018-07-01" "2018-07-02" "2018-07-03"

xts::endpoints给出每个月最后一次观察的索引,总是从0开始:

library(xts)
endpoints(month, "months") 
# [1]  0 13 16

因此,如果您添加 1,您将获得下个月第一个可用日期的索引,方便地,0 将是第 1 个月的第 1 天的索引:

endpoints(month, "months") + 1
# [1]  1 14 17

虽然最后一个值没有意义,所以我们放弃它:

head(endpoints(month, "months") + 1, -1)
# [1]  1 14

我们最终得出您的解决方案:

first.values <- month[head(endpoints(month, "months") + 1, -1)]
# [1] "2018-06-18" "2018-07-01"

另一种方法:

month <- as.xts(month)
first_as_list <- lapply(split(month,f="month"), function(x) index(x)[1])
do.call(c,first_as_list)
# [1] "2018-06-18" "2018-07-01"