9

伙计们,通常当您执行以下操作时:

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

rollapply从 10 个元素可用的那一刻开始计算值是非常正确的。

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?

4

2 回答 2

10

rollapplyin zoo 可以通过指定来做到这一点partial=TRUE,例如

> 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
于 2011-01-28T15:37:27.390 回答
4

为什么不在一开始就用 9 个 NA 填充系列呢?绝对比“丑陋的循环”更好:

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)
于 2011-01-28T15:39:33.240 回答