The moving average of the previous three values ​​in R

The zoo package has a rollmean function that allows you to make moving averages. rollmean(x,3) will take the previous, current, and next value (for example, 4, 6, and 2) in the table below. This is shown in the second column.

 x rollmean ma3 4 6 4.0 2 4.3 5 3.0 4.0 2 6.3 4.3 12 6.0 3.0 4 6.0 6.3 2 6.0 

I would like to do the same job, but averaging the previous 3 values ​​in the fourth row. This is displayed in the third column. Can someone tell me the name of the function that will help to do this?

+6
source share
3 answers

I struggled to find a simple function for moving averages that had some flexibility to do what I needed. I finally wrote a couple of functions that extend one, based on the filter function that rinni gives above in the comment (but which by itself will not work, because it will include the current observation for an average of 3 periods).

  • Moving average function that includes current observation

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

     mavback <- function(x,n){ a<-mav(x,1) b<-mav(x,(n+1)) c<-(1/n)*((n+1)*b - a) return(c) } 
  • Moving average function backwards, not counting the current obs, based on [h2] readings starting from [h1] periods ago

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

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

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

... but you still have to lag behind 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) 
+10
source

A simpler implementation of the w_i_l_l mavback function, based on its mav function

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

0
source

Source: https://habr.com/ru/post/943539/


All Articles