3

Given

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

I want to be be able to aggregate to the following:

> z
 4  8  10 
 10 26 19

I have tried the following 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 looks most promising but I would have to customize a lag?

bob
  • 81
  • 1
  • 4

1 Answers1

1

The partial argument always applies to both ends; however, one can specify the width for each element separately by using a vector for the width argument and then subset 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 fix up the times (using ok from above):

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

3) This could 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)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341