鉴于
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
非常感谢任何帮助。第二个看起来最有希望,但我必须定制滞后?
答案 0 :(得分: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.zoo
(使用上面的ok
)完成此操作:
tt <- na.locf(replace(time(z), !ok, NA), fromLast = TRUE) # 4 4 4 4 8 8 8 8 10 10
aggregate(z, tt, sum)