Search code examples
rmoving-average

r two year moving average with a reference year


This is my dataset

  Year   Pct
  2011   -97%
  2010   -95%
  2009   -90%
  2008   -72%
  2007   -40%
  2006    NA
  2005    47%
  2004    71%
  2003    -25%
  2002    116%
  2001    -5%

I am trying to estimate two year moving average for years 2001-2006 and second moving average from years 2006-2011

  Year    Pct   MovAvg
  2011   -97%   (-97  +  -95)/2
  2010   -95%   (-95  +  -90)/2
  2009   -90%   (-90  +  -72)/2
  2008   -72%   (-72  +  -40)/2
  2007   -40%   NA 
  2006    NA    NA
  2005    47%   (47  +  71)/2
  2004    71%   (71  + -25)/2
  2003    -25%  (-25 + 116 )/2
  2002    116%  (116 - 5)/2
  2001    -5%   NA

I know apply(embed(x, k), 1, mean) provides a two year rolling average, but I am not sure how to implement this logic in two separate time windows 1st between (2001 - 2006), 2nd between (2006-2011)

Any suggestion is much appreciated. Thanks.


Solution

  • Replace the value of Pct for 2006 with NA (I'm calling your data frame x):

    x[x$Year == 2006, "Pct"] <- NA
    

    Then calculate the moving average. You'll need to add 1 NA to the end to get the length to match.

    x$MovAvg <- c(
      apply(embed(x$Pct, 2), 1, mean),
      NA
    )
    
       Year Pct MovAvg
    1  2011 -97  -96.0
    2  2010 -95  -92.5
    3  2009 -90  -81.0
    4  2008 -72  -56.0
    5  2007 -40     NA
    6  2006  NA     NA
    7  2005  47   59.0
    8  2004  71   23.0
    9  2003 -25   45.5
    10 2002 116   55.5
    11 2001  -5     NA