我是R的新手,我正在尝试使用扩大的窗口(即每个日期t使用不超过t的数据)运行滚动回归,并在数据框中按类别列分组使用两个自变量。
例如,在下面的数据帧中,我想使用所有行直到感兴趣的行,提取按类别K分组的lm(return〜regress1 + regress 2)系数。因此,对于第2行,用于回归的数据集将为第1行:2,对于第3行将为第1行:3,对于第4行将仅为第4行,因为它是分类变量K = B的第一行。
myinput <- data.frame(K = c("A", "A", "A", "B", "B", "B", "C", "C", "C"),
date = c(1:3) , return = rnorm(9), regress1 = rnorm(9), regress2 = rnorm(9))
我在Rolling regression with expanding window in R上找到了一个关于此主题的非常有用的主题,但是我很难将其应用于我的数据集。
如果有人可以帮助我了解我需要如何适应他们所使用的方法,将不胜感激。谢谢。
答案 0 :(得分:1)
使用在结尾处的注释中可重复显示的myinput
,定义函数reg
来执行回归。然后利用rollapplyr
为width
等于date
的{{1}}参数,利用date
在组内为1、2、3等的事实,因此等于行回归。最后,cbind
将结果返回到原始数据帧。
library(zoo)
reg <- function(x) coef(lm(as.data.frame(x)))
r <- rollapplyr(zoo(myinput[3:5]), myinput$date, reg, by.column=FALSE, coredata=FALSE)
cbind(myinput, coef = coredata(r))
给予:
K date return regress1 regress2 coef.(Intercept) coef.regress1 coef.regress2
1 A 1 -0.56047565 -0.4456620 0.7013559 -0.56047565 NA NA
2 A 2 -0.23017749 1.2240818 -0.4727914 -0.47231761 0.1978137 NA
3 A 3 1.55870831 0.3598138 -1.0678237 0.15985654 -0.9479906 -1.6294374
4 B 1 0.07050839 0.4007715 -0.2179749 0.07050839 NA NA
5 B 2 0.12928774 0.1106827 -1.0260044 0.15171486 -0.2026254 NA
6 B 3 1.71506499 -0.5558411 -0.7288912 1.05050327 -2.0789081 0.6735997
7 C 1 0.46091621 1.7869131 -0.6250393 0.46091621 NA NA
8 C 2 -1.26506123 0.4978505 -1.6866933 -1.93165311 1.3389399 NA
9 C 3 -0.68685285 -1.9666172 0.8377870 -0.14625482 0.6376389 0.8515213
set.seed
才能使结果可再现。我们使用了这个:
set.seed(123)
myinput <- data.frame(K = c("A", "A", "A", "B", "B", "B", "C", "C", "C"),
date = 1:3, return = rnorm(9), regress1 = rnorm(9), regress2 = rnorm(9))