Search code examples
rsmoothing

Moving average with varying window size


I am using zoo::rollmean to calculate a moving average. However, the windows on which each value is averaged is of a constant size k (I suppose for performance reason in rollmean implementation).

Is there an R implementation of moving average which would accept a dynamic window?

toSmoothed   = c(1,2,3,2,1,2,3,2)
dynamicRange = c(1,2,1,2,1,2,1,2)
foo(toSmoothed, dynamicRange, fill = NA, align = "left") # please notice the aligned left
# return
# c(1,2.5,3,1.5,1,2.5,3,NA)

Solution

  • zoo::rollapply can be useful here. Try:

    zoo::rollapply(toSmoothed, dynamicRange, FUN = mean, fill = NA, align = "left")
    [1] 1.0 2.5 3.0 1.5 1.0 2.5 3.0  NA