Search code examples
rzoomoving-averageragged

R and Zoo: moving average with ragged data?


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

  1. Using rollmean when there are missing values (NA)

Solution

  • Depending on what you're looking for, What about:

       rollapply(hh, 5, mean, na.rm = TRUE)
       [1] 3 4 4 3 3 3 1 1
    

    or

       rollapply(hh, 4, mean, na.rm = TRUE)
       [1]   3   3   4   4   3   3   1   1 NaN