I want to calculate moving averages to fill the NA entries with the known entries 3, 5 and 1. How can I do this with the package zoo in R?
Input
> library(zoo)
> hh <- c(NA, NA, NA, 3, NA, 5, NA, 1, NA, NA, NA, NA)
Fails
Fail with rollmean
> rollmean(hh,na.omit=TRUE,k=1) [1] NA NA NA NA NA NA NA NA NA NA NA NA > rollmean(hh,4, na.omit=TRUE,k=1) [1] NA NA NA NA NA NA NA NA NA NA NA NA > rollmean(hh,4, na.rm=TRUE,k=1) [1] NA NA NA NA NA NA NA NA NA NA NA NA
Fail with Rollapply
> rollapply(hh, 4, function(x) mean(x)) [1] NA NA NA NA NA NA NA NA NA
Intended output something like
> COMMAND(hh, movingAverageNumber, function(x) mean(x)) [1] 3 3.3 3.4 3 4 5 3 1 2 1.5 1.2 1 0.8
Related
Depending on what you're looking for, What about:
or