r - 了解函数端点
问题描述
我有一个时间序列的回报。在第一列中,我有我所有的日期。有了这个功能(搜索小时),我终于设法得到了每个月的第一个值。
问题是,第一天并不总是第一个值。有时是第 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 将是第一个月的第一天的索引:
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"
推荐阅读
- html - 背景图像未完全显示在平板电脑中
- jquery - 带有 jquery 的变体产品脚本
- python - django中后台任务处理的简单方法
- tensorflow - 如何使用带有批量标准化层的预训练 keras 模型?
- r - R中具有多个电子邮件收件人的网络分析
- javascript - 动态删除localstorage中的li项
- azure-cosmosdb - Cosmos DB ExecuteStoredProcedureAsync 未返回响应
- java - 组件之间的 Java swing 通信
- hana - 重新启动后必须重新配置 SAP HANA Express
- powerbi - PowerBI/DAX:明细表总和