Calculating rolling means is easy:
library(data.table)
library(zoo)
DT <- data.table(Y = rnorm(1000), X = rnorm(1000),
key.group = rep(c('a', 'b', 'c', 'd'), each = 250))
DT[, Average.Y := rollapply(Y, width = 12, mean)]
But how do I run rolling regressions (by group) with data.table
and store the coefficient of interest, without extracting the values to another object if possible? Is this feasible?
This attempt does not work:
DT[, coefficient := rollapply(.SD, 20, function(x) {
the.coefficient <- lm(Y ~ X, data = x)$coefficients[2];
return(the.coefficient)}), by = key.group]