9

Guys, normally when you do something like:

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

Quite rightly rollapply will start calculating the value from the moment 10 elements are available.

Unfortunately I need something that uses as much data as possible for the fist 10 observations, essentially a growing window of data till there is enough data to use a sliding window, e.g. 1, 1:2, 1:3, 1:4, etc. till we have at least 10 elements and then slide the window as usual.

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

Dr G
  • 3,987
  • 2
  • 19
  • 25

2 Answers2

10

rollapply in zoo can do that 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
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Seems like `rollapply` function definition has been changed. The function call should now look like - `rollapply(1:20, 3, FUN = sum, align="right", partial = TRUE)` – steadyfish Apr 29 '16 at 14:00
4

Why not just pad the series with 9 NAs 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)
Prasad Chalasani
  • 19,912
  • 7
  • 51
  • 73