gpt4 book ai didi

r - "cumulative"回归向量化

转载 作者:行者123 更新时间:2023-12-01 08:11:23 25 4
gpt4 key购买 nike

我有数据

 dat <- data.frame(t=1:100,y=rnorm(100),x1=rnorm(100)),x2=rnorm(100))

其中 t 给出时间点。我想根据前面的时间点在每个时间点在 x1x2 上回归 y

我可以创建一个循环

reg <- matrix(rep(NA,3*nrow(dat),ncol=3)
for(i in 11:nrow(dat)){
reg[i,] <- coefficients(lm(y ~ x1 + x2, data=dat[1:i,]))
}

但我想知道是否有人知道矢量化它的方法,也许使用 data.table

最佳答案

我们可以使用非等自连接来获取你喜欢的表:

library(data.table)
setDT(dat)
# not clear if you wanted points _strictly_ before present,
# but the fix is basically clear -- just add nomatch = 0L to skip the first row
dat[dat, on = .(t <= t), allow.cartesian = TRUE]
t y x1 x2
1: 1 -0.51729096 0.1765509 1.06562278
2: 2 -0.51729096 0.1765509 1.06562278
3: 2 0.85173679 -0.7801053 0.05249113
4: 3 -0.51729096 0.1765509 1.06562278
5: 3 0.85173679 -0.7801053 0.05249113
---
5046: 100 1.03802913 -2.7042756 2.05639758
5047: 100 -1.29122593 0.9013410 0.77088748
5048: 100 0.08262791 0.4135725 0.92694074
5049: 100 -0.93397320 0.2719790 -0.26097185
5050: 100 -1.23897617 0.9008160 0.61121185
i.y i.x1 i.x2
1: -0.5172910 0.1765509 1.06562278
2: 0.8517368 -0.7801053 0.05249113
3: 0.8517368 -0.7801053 0.05249113
4: -0.5080630 -2.0701757 -1.01573263
5: -0.5080630 -2.0701757 -1.01573263
---
5046: -1.2389762 0.9008160 0.61121185
5047: -1.2389762 0.9008160 0.61121185
5048: -1.2389762 0.9008160 0.61121185
5049: -1.2389762 0.9008160 0.61121185
5050: -1.2389762 0.9008160 0.61121185

(有点困惑,但在 t <= t 中,LHS t 指的是 LHS dat,RHS t 指的是 RHS dat)

从这里我们只需要按 t 分组并运行回归:

dat[dat, on = .(t <= t), allow.cartesian = TRUE
][ , as.list(coef(lm(y ~ x1 + x2))), keyby = t
# (only adding head here to limit output)
][ , head(.SD)]
# t (Intercept) x1 x2
# 1: 1 -0.5172910 NA NA
# 2: 2 -0.2646369 -1.43105510 NA
# 3: 3 9.1879448 9.96212179 -10.7580819
# 4: 4 -0.3504059 -0.36654096 0.4523271
# 5: 5 -0.1681879 -0.06670494 0.3553107
# 6: 6 1.2108223 1.04082291 -0.6947567

关于r - "cumulative"回归向量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com