Search code examples
rdataframezoorollapply

Result-feeding rolling window or rollapply with cumsum


Suppose I have the following zoo object:

x.orig <- read.zoo(data.frame(date=seq(as.Date('2020-01-01'), as.Date('2020-01-10'), 1), v=c(1,2,3,100,4,5,1000,8,8,10)))
2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07 2020-01-08 2020-01-09 2020-01-10 
         1          2          3        100          4          5       1000          8          8         10 

I would like to compute a rolling sum of width=seq_along(x.orig) as follows:

2020-01-01 1
2020-01-02 1 + 2                                   #2020-01-01 + 2020-01-02
2020-01-03 1 + (1 + 2) + 3                         #2020-01-01 + 2020-01-02 + 2020-01-03
2010-01-04 1 + (1 + 2) + (1 + (1 + 2) + 3) + 100   #2020-01-01 + 2020-01-02 + 2020-01-03 + 2020-01-04
...

I would imagine the way to do this would be to result-feed x in some way so that x is updated after each rollapply loop so that the next rollapply iteration picks up the modified value in its window but am just not sure how to write it...


Solution

  • A simple loop will do it:

    v <- x.orig
    for(i in seq_along(v)) v[i] <- sum(head(v, i))
    

    which results in this zoo object:

    > v
    2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07 
             1          3          7        111        126        253       1501 
    2020-01-08 2020-01-09 2020-01-10 
          2010       4020       8042 
    

    rollapply

    If you wanted to wrap this within a rollapplyr of width 3, say:

    accum <- function(x) { for(i in seq_along(x)) x[i] <- sum(head(x, i)); tail(x, 1) }
    rollapplyr(x.orig, 3, accum)