2

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)
pepece
  • 307
  • 4
  • 14

2 Answers2

3

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
nghauran
  • 6,402
  • 2
  • 18
  • 27
1

Not sure if there is anything in a package, but you could do something like this...

foo <- function(toSmoothed, dynamicRange){
  x <- c(0, cumsum(toSmoothed))
  lower <- 1:length(toSmoothed)
  upper <- lower+dynamicRange
  x <- (x[upper]-x[lower])/(upper-lower)
  return(x)
}

foo(toSmoothed, dynamicRange)
[1] 1.0 2.5 3.0 1.5 1.0 2.5 3.0  NA
Andrew Gustar
  • 15,825
  • 18
  • 28