简体   繁体   中英

'Subscript out of bounds.' in period.apply

I have an xts of 1's and 0's indicating some event on a date. I would like to have R loop through each Friday in the index and see if there are any 1's for that week. I have this:

> 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

As you can see, I am getting the error. Any help?

EDIT:

So I figured out the error. 'INDEX' is supposed to be a vector or row numbers, not dates. This works:

period.apply(this, INDEX=c(0, which(index(this) %in% that)), FUN=function(x) max(x))

However, I am stuck on the original problem. I dot not know how to get the first occurrence of the 1 in the series. I tried this:

> 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

But I do not know what these are. I am guessing the index doesnt go through with 'x' to be passed to the function.

Any ideas on how to do what I am attempting?

I would like to have R loop through each Friday in the index and see if there are any 1's for that week

Not clear what you want, so this counts the number of events in the week for you.

7309, 7310 correspond to the numeric values of the dates you're returning with index(x)[....]

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

If you want the first day of each week where your xts object has a value of 1, you can:

  1. split your xts object into a list of data for each week,
  2. lapply a function to find the first observation equal to 1,
  3. rbind the list into a single xts object.

And here's an example:

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))

And here's the sample data and result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM