R and Zoo: moving average with ragged data?

998 views Asked by At

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)
2

There are 2 answers

3
Rhodo On BEST ANSWER

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
0
manotheshark On

Assuming you want the rolling mean for four values (you pass k=1 to rollmean), you need to tell mean to drop the NA

library(zoo)
rollapply(hh, 4, function(x) mean(x, na.rm=TRUE))

[1]   3   3   4   4   3   3   1   1 NaN

Although this returns something different than your desired output. You'll need to explain this further if you want something different.