Calculating moving average

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

    Using cumsum should be sufficient and efficient. Assuming you have a vector x and you want a running sum of n numbers

    cx <- c(0,cumsum(x))
    rsum <- (cx[(n+1):length(cx)] - cx[1:(length(cx) - n)]) / n
    

    As pointed out in the comments by @mzuther, this assumes that there are no NAs in the data. to deal with those would require dividing each window by the number of non-NA values. Here's one way of doing that, incorporating the comment from @Ricardo Cruz:

    cx <- c(0, cumsum(ifelse(is.na(x), 0, x)))
    cn <- c(0, cumsum(ifelse(is.na(x), 0, 1)))
    rx <- cx[(n+1):length(cx)] - cx[1:(length(cx) - n)]
    rn <- cn[(n+1):length(cx)] - cn[1:(length(cx) - n)]
    rsum <- rx / rn
    

    This still has the issue that if all the values in the window are NAs then there will be a division by zero error.

提交回复
热议问题