如何在data.table中运行滚动回归并将系数存储在列中?

时间:2016-04-12 02:36:22

标签: r data.table zoo

计算滚动方式很简单:

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]

0 个答案:

没有答案