1

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]
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Konstantinos
  • 4,096
  • 3
  • 19
  • 28
  • possible duplicate: Fast linear regression by group http://stackoverflow.com/questions/29803993/fast-linear-regression-by-group – chinsoon12 Apr 13 '16 at 02:15

0 Answers0