问题描述
如何使用 rollapply
(或其他一些 R 函数)在函数处理数据时增大窗口大小.换句话说,第一个应用适用于第一个元素,第二个适用于前两个元素,第三个适用于前三个元素等.
How would one use rollapply
(or some other R function) to grow the window size as the function progresses though the data. To phrase it another way, the first apply works with the first element, the second with the first two elements, the third with the first three elements etc.
推荐答案
如果您希望应用 min
、max
、sum
或prod
,这些函数已经有了它们的累积对应项:
If you are looking to apply min
, max
, sum
or prod
, these functions already have their cumulative counterparts as:
cummin
、cummax
、cumsum
和 cumprod
要在增长/扩展窗口上应用更多奇异函数,您只需使用 sapply
To apply more exotic functions on a growing / expanding window, you can simply use sapply
例如
# your vector of interest
x <- c(1,2,3,4,5)
sapply(seq_along(x), function(y,n) yourfunction(y[seq_len(n)]), y = x)
对于一个基本的动物园对象
For a basic zoo object
x.Date <- as.Date("2003-02-01") + c(1, 3, 7, 9, 14) - 1
x <- zoo(rnorm(5), x.Date)
# cumsum etc will work and return a zoo object
cs.zoo <- cumsum(x)
# convert back to zoo for the `sapply` solution
# here `sum`
foo.zoo <- zoo(sapply(seq_along(x), function(n,y) sum(y[seq_len(n)]), y= x), index(x))
identical(cs.zoo, foo.zoo)
## [1] TRUE
这篇关于rollapply 变化 - 增长窗口函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!