title: Rolling mean (moving average) by group/id with dplyr
body: <p>I have a longitudinal follow-up of blood pressure recordings.</p>
  
  <p>The value at a certain point is less predictive than is the moving average (rolling mean), which is why I'd like to calculate it. The data looks like</p>
  
  <pre><code>test &lt;- read.table(header=TRUE, text = "
    ID  AGE   YEAR_VISIT  BLOOD_PRESSURE  TREATMENT
    1 20  2000    NA 3
    1 21  2001    129 2
    1 22  2002    145 3
    1 22  2002    130 2
    2 23  2003    NA  NA
    2 30  2010    150 2
    2 31  2011    110 3
    4 50  2005    140 3
    4 50  2005    130 3
    4 50  2005    NA  3
    4 51  2006    312 2
    5 27  2010    140 4
    5 28  2011    170 4
    5 29  2012    160 NA
    7 40  2007    120 NA
                     ")
  </code></pre>
  
  <p>I'd like to calculate a new variable, called BLOOD_PRESSURE_UPDATED. This variable should be the moving average for BLOOD_PRESSURE and have the following characteristics:</p>
  
  <ul>
  <li>A moving average is the current value plus the previous value divided by two.</li>
  <li>For the first observation, the BLOOD_PRESSURE_UPDATED is just the current BLOOD_PRESSURE. If that is
  missing, BLOOD_PRESSURE_UPDATED should be the overall mean.</li>
  <li>Missing values should be filled in with nearest previous value.</li>
  </ul>
  
  <p>I've tried the following:</p>
  
  <pre><code>test2 &lt;- test %&gt;%
    group_by(ID) %&gt;%
    arrange(ID, YEAR_VISIT) %&gt;%
    mutate(BLOOD_PRESSURE_UPDATED = rollmean(x=BLOOD_PRESSURE, 2)) %&gt;%
  ungroup()
  </code></pre>
  
  <p>I have also tried <code>rollaply</code> and <code>rollmeanr</code> without succeeding.</p>