Moving average of previous three values in R

纵饮孤独 提交于 2019-11-27 04:41:25
w_i_l_l

I struggled searching for a simple function for moving averages that had some flexibility to do what I needed. I finally wrote a couple functions extending the one based on the filter function which rinni gives above in the comment (but which itself won't work because it will include the current observation in the 3 period average).

  1. Moving average function that includes the current observation

    mav <- function(x,n){filter(x,rep(1/n,n), sides=1)} 
    
  2. Moving average function that does not include the current observation

    mavback <- function(x,n){
      a<-mav(x,1)
      b<-mav(x,(n+1))
      c<-(1/n)*((n+1)*b - a)
      return(c)
    }
    
  3. Backward looking moving average function, not including current obs, based on [h2] readings starting [h1] periods back

    mavback1<-function(x,h1,h2){
      a<-mavback(x,h1)
      b<-mavback(x,h1-h2)
      c<-(1/h2)*(h1*a -(h1-h2)*b)
      return(c)
    }
    

You can use rollmean, but set align='right'. Or you could use rollmeanr, which has align='right' as the default.

ma3 <- rollmeanr(x[,1],3,fill=NA)

...but you would still need to lag the result. Another solution is to use rollapply with a list for the width argument:

ma3 <- rollapplyr(x[,1],list(-(3:1)),mean,fill=NA)

A simplier implementation of w_i_l_l's mavback function based on his mav function

mavback <- function(x,n){ filter(x, c(0, rep(1/n,n)), sides=1) }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!