title: R - Calculating 12 month moving average on panel data
body: <p>First, full disclosure.  I attempted to do this strictly in MS Access with correlated subqueries, and had some help on this post <a href="https://stackoverflow.com/questions/19299039/12-month-moving-average-by-person-date">12 month moving average by person, date</a>. I originally thought my data would be small enough to chug through, but it is awful.  As an alternative, I'm going to try running this in R and then writing results to a new table in MS Access.  I have data such that I have the following fields:</p>
  
  <pre><code>rep, cyc_date, amt
  </code></pre>
  
  <p>Following the linked example by Andrie for a rolling 5-year period (as opposed to the 5-year average) <a href="https://stackoverflow.com/questions/4954088/r-calculating-5-year-averages-in-panel-data">R: Calculating 5 year averages in panel data</a>, I am trying to get rolling 12 month average for <code>amt</code> field by <code>rep</code>.  Here is my code:</p>
  
  <pre><code>library(zoo)
  library(plyr)
  library(RODBC)
  
  # Pull data from local MS Access database.  The referenced sqlFetch is a query
  # that pulls the data, ordered by `rep`, then `cyc_date`
  
  channel &lt;- odbcConnectAccess2007("C://MyDB.accdb")
  data &lt;- data.frame(sqlFetch(channel, "MyView"))
  
  # Ensure coercion of `cyc_date` to date type
  data$cyc_date &lt;- as.Date(data$cyc_date)
  
  # Function (take from post above)
  rollmean12 &lt;- function(x) {
                   rollmean(x, 12)
                }
  # Calculate rolling average by person
  rollvec &lt;- ddply(data, .(data$rep), rollmean12(data$amt))
  </code></pre>
  
  <p>Unfortunately, this doesn't work.  I'm getting the following error:</p>
  
  <pre><code>Error in llply(.data = .data, .fun = .fun, ..., .progress = .progress,  : 
  .fun is not a function.
  </code></pre>
  
  <p>I'm not sure why this is happening.  Do I need to explicitly convert <code>data</code> to a <code>zoo</code> object?  If so, not sure how to handle the extra dimensionality resulting from the <code>person_id</code> field.  Any help would be very much appreciated.</p>