Function rollapply
in package zoo gets you close:
> require(zoo)
> TS <- zoo(c(4, 5, 7, 3, 9, 8))
> rollapply(TS, width = 3, by = 2, FUN = mean, align = "left")
1 3
5.333333 6.333333
It just won't compute the last value for you as it doesn't contain 3 observations. Maybe this will be sufficient for your real problem? Also, note that the returned object has the indices you want as the names
of the returned vector.
Your example is making an assumption that there is an unobserved 0 in the last window. It might be more useful or realistic to pad with an NA
to represent the missing information and tell mean
to handle missing values. In this case we will have (8+9)/2 as our final windowed value.
> TS <- zoo(c(4, 5, 7, 3, 9, 8, NA))
> rollapply(TS, width = 3, by = 2, FUN = mean, na.rm = TRUE, align = "left")
1 3 5
5.333333 6.333333 8.500000