Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 理解函数端点_R_Xts_Endpoints_Dayofmonth - Fatal编程技术网

R 理解函数端点

R 理解函数端点,r,xts,endpoints,dayofmonth,R,Xts,Endpoints,Dayofmonth,我有一个时间序列的回报。在第一栏中,我有我所有的日期。通过这个函数(搜索小时数),我最终获得了每个月的第一个值 问题是,并非总是第1天是第一个值。有时是第2天、第3天、第4天、第5天等等 幸运的是,有了此功能,一切都能正常工作: library(xts) month<- data[,1] ## all my dates first.values <- month[head(endpoints(month, "months") + 1, -1)] 库(xts) 月让我们准备样

我有一个时间序列的回报。在第一栏中,我有我所有的日期。通过这个函数(搜索小时数),我最终获得了每个月的第一个值

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

幸运的是,有了此功能,一切都能正常工作:

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

月让我们准备样本数据:

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"
因此,如果您添加
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"

first.values您可能想提及这是什么编程语言。对不起!它是R统计软件。而且,
endpoints
不是一个基本的R函数,所以你应该包括你正在使用的任何软件包的名称。如果你发现这段代码是这样的,你应该在你的问题主体中提供一个到那篇文章的链接。对于
head
,-1表示返回向量/data.frame/matrix的所有值,除了最终值。有关更多详细信息,请参阅帮助页
?head
。顺便说一句,在编写代码时,我通常会花20%(或更多)的时间查看函数的帮助文件,以更好地了解它们是如何工作的。非常感谢Moody_Mudscapper!我感谢你花时间给出如此详细的答案不客气,我添加了另一种计算方法,您可能会发现更直观。考虑标记问题,如果它解决了您的发行。@ j.POP:欢迎到StAdvOp溢出。请看。
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"