计算滚动方式很简单:
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)]
但是如何使用data.table
运行滚动回归(按组)并存储感兴趣的系数,如果可能的话,不将值提取到另一个对象?这可行吗?
此尝试不起作用:
DT[, coefficient := rollapply(.SD, 20, function(x) {
the.coefficient <- lm(Y ~ X, data = x)$coefficients[2];
return(the.coefficient)}), by = key.group]