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
  • 360
  • 5
  • 17

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,648
  • 2
  • 20
  • 29
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
  • 17,295
  • 1
  • 22
  • 32