title: Decay function (adstock) with pooled models in R
body: <p>I'm currently using the following code to create a decay (adstock) function of decay rate y:</p>
  
  <pre><code>adstock &lt;- function(x, decay=y) filter(x, decay, method = "recursive")
  </code></pre>
  
  <p>And this gives the desired result.</p>
  
  <p>However, if I have a pooled set of data, such that each region is grouped together and runs chronologically, the start of the second region has the decay left over from the end of the first. Similarly with the third region etc...</p>
  
  <p>What would be the best way to ensure the first observation of the (n>1) regions remains equal to the original value, but all subsequent values have the decay formula applied?</p>
  
  <p>For example:</p>
  
  <pre><code>Weeks &lt;- c("01/01/2012","08/01/2012","15/01/2012","22/01/2012","29/01/2012","01/01/2012","08/01/2012","15/01/2012","22/01/2012","29/01/2012","01/01/2012","08/01/2012","15/01/2012","22/01/2012","29/01/2012")
  Regions &lt;- c("North","North","North","North","North","South","South","South","South","South","West","West","West","West","West")
  Variable &lt;- c(5,6,4,8,6,19,20,5,7,8,0,5,4,6,7)
  exampledata &lt;- data.frame(Weeks, Regions, Variable)
  </code></pre>
  
  <p>The new function should run the decay function only for each region. So row 11, 01/01/2012 for the "West" region, should always be zero.</p>