我有一个1和0的xts指示某个日期的事件。我希望每个星期五在索引中都有R循环,并查看该周是否有任何1。我有这个:'下标越界'。在period.apply
> this = xts(sample(c(0,1), replace=TRUE, size=10),
order.by = seq.Date(as.Date('1990-01-05'), by = 1, length.out=10))
> this
[,1]
1990-01-05 0
1990-01-06 1
1990-01-07 0
1990-01-08 0
1990-01-09 0
1990-01-10 0
1990-01-11 1
1990-01-12 0
1990-01-13 0
1990-01-14 0
> that = index(this)[.indexwday(this) == 5]
> that
[1] "1990-01-05" "1990-01-12"
> period.apply(this, INDEX=that, FUN=function(x) max(x))
Error in `[.xts`(x, (INDEX[y] + 1):INDEX[y + 1]) :
subscript out of bounds
正如你所看到的,我得到的错误。任何帮助?
编辑:
所以我想出了错误。 'INDEX'应该是一个向量或行号,而不是日期。这个工程:
period.apply(this, INDEX=c(0, which(index(this) %in% that)), FUN=function(x) max(x))
但是,我卡在原来的问题。我不知道如何获得系列中第一个出现的1。我试过这个:
> period.apply(this, INDEX=c(0, which(index(this) %in% that)), FUN=function(x) index(x)[min(which(x==1))])
[,1]
1990-01-05 7309
1990-01-12 7310
但我不知道这些是什么。我猜测索引不会通过'x'传递给函数。
关于如何做我所尝试的任何想法?