title: Constructing moving average over a categorical variable in R
body: <p>I'm looking to construct a moving average while aggregating a timeseries dataset over two categorical variables. While I've seen a few other tutorials, none of them seem to capture the specific task I'd like to achieve.</p>
  
  <p>My original dataset (<code>df</code>) has rows for each individual (<code>id</code>) for a series of dates ranging from 0-180 (<code>Days</code>).  Individuals can be members of one of two subsets of data (<code>Group</code>). </p>
  
  <p>I then aggregate this data frame to get a daily mean for the two groups.</p>
  
  <pre><code>library(plyr)
  summary &lt;- ddply(df, .(Group,Days), summarise,
                        DV = mean(variable), resp=length(unique(Id)))
  </code></pre>
  
  <p>The next step, however, is to construct a moving average <em>within</em> the two groups. In the sample dataframe below, I've just constructed a 5-day mean using the previous 5 days.</p>
  
  <pre><code>Group       Days  DV    5DayMA
  exceeded    0   2859    
  exceeded    1   2948    
  exceeded    2   4412    
  exceeded    3   5074    
  exceeded    4   5098    4078
  exceeded    5   5147    4536
  exceeded    6   4459    4838
  exceeded    7   4730    4902
  exceeded    8   4643    4815
  exceeded    9   4698    4735
  exceeded    10  4818    4670
  exceeded    11  4521    4682
  othergroup  0   2859    
  othergroup  1   2948    
  othergroup  2   4412    
  othergroup  3   5074    
  othergroup  4   5098    4078
  othergroup  5   5147    4536
  othergroup  6   4459    4838
  othergroup  7   4730    4902
  othergroup  8   4643    4815
  othergroup  9   4698    4735
  othergroup  10  4818    4670
  othergroup  11  4521    4682
  </code></pre>
  
  <p>Any thoughts on how to do this?</p>