Calculating moving average

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

    In fact RcppRoll is very good.

    The code posted by cantdutchthis must be corrected in the fourth line to the window be fixed:

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

    Another way, which handles missings, is given here.

    A third way, improving cantdutchthis code to calculate partial averages or not, follows:

      ma <- function(x, n=2,parcial=TRUE){
      res = x #set the first values
    
      if (parcial==TRUE){
        for(i in 1:length(x)){
          t<-max(i-n+1,1)
          res[i] = mean(x[t:i])
        }
        res
    
      }else{
        for(i in 1:length(x)){
          t<-max(i-n+1,1)
          res[i] = mean(x[t:i])
        }
        res[-c(seq(1,n-1,1))] #remove the n-1 first,i.e., res[c(-3,-4,...)]
      }
    }
    

提交回复
热议问题