Rollapply with a “growing” window

Guys, usually when you do something like:

tmp = zoo(rnorm(100), 1:100) rollapply(tmp, 10, function(x) quantile(x, 0.05), align="right") 

rollapply right, rollapply will start calculating the value from the moment when 10 elements are available.

Unfortunately, I need something that allows you to use as much data as possible for the first 10 observations, essentially a growing data window, until there is enough data to use a sliding window, for example. 1, 1: 2, 1: 3, 1: 4, etc., until we have at least 10 elements, and then, as usual, slide the window.

Is there a better way to do this than an ugly loop?

+8
r zoo
source share
2 answers

Why not just put the series with 9 NA at the beginning? Definitely better than ugly for loops:

 tmp = zoo(c(rep(NA,9), rnorm(100)), 1:109) zoo(rollapply(tmp, 10, function(x) quantile(x, 0.05, na.rm = TRUE), align="right"), 1:100) 
+4
source share

rollapply in zoo can do this by specifying partial=TRUE , e.g.

 > library(zoo) > > rollapplyr(zoo(1:20), 3, sum, partial=TRUE) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 
+10
source share

All Articles