title: Moving Average for multiple ID's, by date, not observation, in R
body: <p>I have a relatively large dataset (over 1000 obs and growing), with an ID code for each person, a date, and a metric value for each person on each date (with some missing values). </p>
  
  <p>I'm looking to add a column of a simple moving average of that metric for each ID, on each date, ideally through a function where I could reproduce it for multiple date windows of the moving average (5-day,20-day, etc) </p>
  
  <p>Using the answer from another rolling avg question answered here, this solution works if I subset the data into a single ID:</p>
  
  <pre><code>rollavgbyperiod &lt;- function(i,window){
    startdate &lt;- dates[i]-window
    enddate &lt;- dates[i]
    interval &lt;- seq(startdate,enddate,1)
  
    tmp &lt;- df[dates %in% interval,"metric"]
    return(mean(tmp$metric))
  }
  
  dates &lt;- as.Date(df$date)
  window &lt;- 5
  Roll.Av &lt;- sapply(1:length(df$date),function(m) rollavgbyperiod(m,window))
  Roll.Av[is.nan(Roll.Av)] &lt;- NA
  </code></pre>
  
  <p>My thought was to use a dplyr summarize after a group_by(df,ID), using the function above, but I'm unable to figure out a working solution for that. </p>
  
  <p>My other approach was trying to split the df into a list by ID, then using lapply on that list, then bringing that list back to one df, but this seems like a cumbersome solution, and again-couldn't find a working solution. </p>
  
  <p>As added context, I'm pulling this data in from an AzureSQL table, which is why I wouldn't be able to just leave it in a list (other uses of this table, like PowerBI-to my knowledge, need tables, correct me if I'm mistaken however). </p>