Calculating moving average

前端 未结 16 1773
夕颜
夕颜 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:37

    You could use RcppRoll for very quick moving averages written in C++. Just call the roll_mean function. Docs can be found here.

    Otherwise, this (slower) for loop should do the trick:

    ma <- function(arr, n=15){
      res = arr
      for(i in n:length(arr)){
        res[i] = mean(arr[(i-n):i])
      }
      res
    }
    

提交回复
热议问题