rollapply for cumulative window

2.4k views Asked by At

I am trying to figure out how to use R rollapply on a data window which expands cumulatively from the beginning of data.

At time t, roll apply should use data in the 1:t range. At time t+1, it should use 1:t+1, and so on.

Thanks a lot John

2

There are 2 answers

0
akrun On

If you need the mean, you could try (using base R functions)

cumsum(v1)/seq_along(v1)
#[1] 4.0 3.0 3.0 2.5 3.0

or

sapply(seq_along(v1), function(i) mean(v1[1:i]))
#[1] 4.0 3.0 3.0 2.5 3.0

data

 v1 <- c(4,2,3,1,5)
0
G. Grothendieck On

1) rollapplyr The width (2nd arg) can be a vector of widths so if x is some input vector and f is some suitable function then:

rollapplyr(x, seq_along(x), f)

For example, if f is sum then the above is the same as cumsum(x) and if f is max then the above is the same as cummax(x).

Achim pointed out that this works too:

rollapplyr(x, length(x), f, partial = TRUE)

2) Reduce The above is likely what you want but, alternately, for certain functions (they must accept two arguments and iterative application must be suitable as the final answer) we can use Reduce in the base of R. For example, cumsum and cummmax correspond to:

Reduce(`+`, x, accumulate = TRUE)
Reduce(max, x, accumulate = TRUE)

Note that these will not give cumulative means:

Reduce(mean, x, accumulate = TRUE) # BAD
Reduce(function(x, y) (x+y)/2, x, accumulate = TRUE) # BAD

although this does give the cumulative mean:

Reduce(`+`, x, accumulate = TRUE) / seq_along(x) # ok

so in summary Reduce will only work in certain restricted cases.