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
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.
If you need the
mean
, you could try (usingbase R
functions)or
data