2017-04-18 62 views
0

我有一个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'传递给函数。

关于如何做我所尝试的任何想法?

回答

0

我想通过每周五有R回路的指数,看看 是否有任何1的那一周

不清楚你想要什么,所以这个计算中的事件数这周为你。

7309,7310对应于你与指数(x)的返回日期的数值[...]

period.apply(this, INDEX=c(0, which(index(this) %in% that)), FUN=function(x) { sum(x==1)}) 
0

如果你想每个星期的第一天,在您的XTS对象具有值为1,您可以:

  1. split您的XTS对象成每星期的数据列表,
  2. lapply一个函数来找到第一个观测等于1,
  3. rbind列表成一个单一的xts对象。

而且这里有一个例子:

set.seed(21) 
this <- xts(sample(0:1, 10, TRUE), seq(as.Date("1990-01-05"), by=1, length.out=10)) 
first1 <- function(x) first(x[x==1]) 
weeklist <- split(this, "weeks") 
week1 <- do.call(rbind, lapply(weeklist, first1)) 

而这里的样本数据和结果:

R> this 
      [,1] 
1990-01-05 1 
1990-01-06 0 
1990-01-07 1 
1990-01-08 0 
1990-01-09 1 
1990-01-10 1 
1990-01-11 0 
1990-01-12 0 
1990-01-13 1 
1990-01-14 1 
R> week1 
      [,1] 
1990-01-05 1 
1990-01-09 1