Given a dataframe containing a timeseries with irrgularly spaced intervals, defined as:
df <- data.frame(date = as.Date("2016-01-01") + ((1:100) + sample(1:5, 100, replace = TRUE)),
data = rnorm(100) )
How can I calculate a rolling sum of the data
column over the previous 30 days, with weights defined by this decay function?
tau <- 0.05
decay = function(tau, day){
exp(-tau * day)
}
The current day's data then has a weight of 1 and the data from 30 days ago has a weight of decay(0.05, 30) = 0.2231302
. Missing days from the input time series should still be accounted for in computing the weights using the decay function.
If possible, I would like to convert the data frame to a zoo
or xts
object and then use the rollapplyr
function or similar, and to do this with dplyr
pipes.