I'm currently using the following code to create a decay (adstock) function of decay rate y:
adstock <- function(x, decay=y) filter(x, decay, method = "recursive")
And this gives the desired result.
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...
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?
For example:
Weeks <- 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 <- c("North","North","North","North","North","South","South","South","South","South","West","West","West","West","West")
Variable <- c(5,6,4,8,6,19,20,5,7,8,0,5,4,6,7)
exampledata <- data.frame(Weeks, Regions, Variable)
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.