Here's sample df:
tt <- as.Date("2000-01-01") + c(1, 2, 5, 6, 7, 8, 10)
z <- zoo(seq_along(tt), tt)
## - fill it out to a daily series, zm, using NAs
## using a zero width zoo series g on a grid
g <- zoo(, seq(start(z), end(z), "day"))
zm <- merge(z, g)
Now if you do:
rollapply(zm, 5, mean, na.rm = TRUE, fill = NA, align = 'right')
This gives you 4 NAs at the beginning. What I want to do is instead when the window is smaller than 5 use a smaller window. So when the data are:
2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 2000-01-08 2000-01-09 2000-01-10 2000-01-11
1 2 NA NA 3 4 5 6 NA 7
Then the result would be:
2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 2000-01-08 2000-01-09 2000-01-10 2000-01-11
1 1.5 1.5 1.5 2 3 4 4.5 4.5 5.5
rollapply(zm, 5, mean, na.rm = TRUE, fill = NA, align = 'right', partial = TRUE)
> rollapply(zm, 5, mean, na.rm = TRUE, fill = NA, align = 'right', partial = TRUE)
2000-01-02 2000-01-03 2000-01-04 2000-01-05 2000-01-06 2000-01-07 2000-01-08 2000-01-09 2000-01-10 2000-01-11
1.0 1.5 1.5 1.5 2.0 3.0 4.0 4.5 4.5 5.5
From help("rollapply")
, in the documentation of the partial
argument:
partial
logical or numeric. If FALSE (default) then FUN is only applied when all indexes of the rolling window are within the observed time range. If TRUE, then the subset of indexes that are in range are passed to FUN. A numeric argument to partial can be used to determin the minimal window size for partial computations.