Calculating moving average

前端 未结 16 1791
夕颜
夕颜 2020-11-21 23:55

I\'m trying to use R to calculate the moving average over a series of values in a matrix. The normal R mailing list search hasn\'t been very helpful though. There doesn\'t s

16条回答
  •  醉酒成梦
    2020-11-22 00:40

    Here is a simple function with filter demonstrating one way to take care of beginning and ending NAs with padding, and computing a weighted average (supported by filter) using custom weights:

    wma <- function(x) { 
      wts <- c(seq(0.5, 4, 0.5), seq(3.5, 0.5, -0.5))
      nside <- (length(wts)-1)/2
      # pad x with begin and end values for filter to avoid NAs
      xp <- c(rep(first(x), nside), x, rep(last(x), nside)) 
      z <- stats::filter(xp, wts/sum(wts), sides = 2) %>% as.vector 
      z[(nside+1):(nside+length(x))]
    }
    

提交回复
热议问题