title: Calculate the Average Based on Date in a Column in r
body: <p>I'm trying to calculate the average values based on the date in a column. With the option to select the number of previous days for example, 4 days. Get the average of the previous 4 records minus the StartDate and roll the average down until there is an EndDate.</p>
  
  <p>I was trying the </p>
  
  <pre><code>tapply(df$Boe, df$ShutinDate, function(x) mean(tail(sort(x), 5)))
  </code></pre>
  
  <p>function but I’m not getting the correct average.</p>
  
  <p>Output</p>
  
  <pre><code>Name    DATE    Values  StartDate   EndDate    Average
  TestA   3/3/2017    50          
  TestA   3/4/2017    75          
  TestA   3/5/2017    25          
  TestA   3/6/2017    100         
  TestA   3/7/2017    100         
  TestA   3/8/2017    50          
  TestA   3/9/2017    80          
  TestA   3/10/2017   90          
  TestA   3/11/2017   25             3/11/2017        
  TestA   3/12/2017   0                           80
  TestA   3/13/2017   0                           80
  TestA   3/14/2017   0                           80
  TestA   3/15/2017   0                           80
  TestA   3/16/2017   50      3/16/2017   
  </code></pre>