3

给定

z <- zoo(c(1:10))

我希望能够汇总到以下内容:

> z
 4  8  10 
 10 26 19

我使用 rollapply 尝试了以下操作,但无济于事:

> rollapply(zoo(c(1:10)), width = 4, FUN = "sum", by = 4, partial = TRUE, align = "right")
 1  5  9 
 1 14 30 
> rollapply(zoo(c(1:10)), width = 4, FUN = "sum", by = 4, partial = TRUE, align = "left")
 1  5  9 
10 26 19 
> rollapply(zoo(c(1:10)), width = 4, FUN = "sum", by = 4, partial = TRUE, align = "center")
 1  5  9 
 6 22 27 

任何帮助将不胜感激。第二个看起来最有希望,但我必须定制一个滞后?

4

1 回答 1

1

论点总是适用于partial两端;但是,可以通过使用向量作为参数分别指定每个元素的宽度,width然后自己对其进行子集化,而不是使用by

library(zoo)

# inputs
z <- zoo(1:10)
k <- 4    

n <- length(z)
w <- rep(1:k, length = n)  # 1 2 3 4 1 2 3 4 1 2 
ok <- w == k | seq(n) == n  # F F F T F F F T F T

rollapplyr(z, w, sum)[ok]

给予:

 4  8 10 
10 26 19 

2)我们可以使用align = "left"然后修复时间(ok从上面使用):

r <- rollapply(z, k, by = k, sum, partial = TRUE, align = "left")
time(r) <- time(z)[ok]

3)这可以使用aggregate.zoook从上面使用)来完成:

tt <- na.locf(replace(time(z), !ok, NA), fromLast = TRUE)  # 4 4 4 4 8 8 8 8 10 10
aggregate(z, tt, sum)
于 2015-05-17T23:59:17.663 回答