R ';下标超出范围;申请

R ';下标超出范围;申请,r,xts,R,Xts,我有一个1和0的xts,表示某个日期的某个事件。我想让R循环通过索引中的每个星期五,看看那一周是否有1。我有这个: > 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和0的xts,表示某个日期的某个事件。我想让R循环通过索引中的每个星期五,看看那一周是否有1。我有这个:

> 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
正如你所看到的,我得到了错误。有什么帮助吗

编辑:

所以我发现了错误。”“索引”应该是一个向量或行号,而不是日期。这项工作:

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”传递给函数

关于如何做我正在尝试的事情有什么想法吗

我想让R循环通过索引中的每个星期五,看看 如果那周有1的话

不清楚你想要什么,所以这会计算你一周内的活动数量

73097310对应于使用索引(x)[..]返回的日期的数值


如果希望每周的第一天xts对象的值为1,可以:

  • 将您的xts对象拆分为每周的数据列表
  • lappy
    查找第一个观测值等于1的函数
  • 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))
    
    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