Roll is applied to partial time series in R
Considering
z <- zoo(c(1:10))
I want to be able to aggregate the following:
> z
4 8 10
10 26 19
I've tried using rollapply but to no avail:
> 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
Any help would be greatly appreciated. The second one looks the most promising, but will I need to adjust the delay?
source to share
The argument partial
always applies to both ends; however, you can set the width for each element separately by using a vector for the argument width
, and then multiply it yourself, instead of using 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]
giving:
4 8 10
10 26 19
2) We could use align = "left"
and then correct the time (using ok
from above):
r <- rollapply(z, k, by = k, sum, partial = TRUE, align = "left")
time(r) <- time(z)[ok]
3) This can be done using aggregate.zoo
(using ok
from above):
tt <- na.locf(replace(time(z), !ok, NA), fromLast = TRUE) # 4 4 4 4 8 8 8 8 10 10
aggregate(z, tt, sum)
source to share