在 data.table 中对几个因变量和自变量循环线性回归并存储结果

Loop a linear regression over several dependant and independant variables in a data.table and store the results

我正在尝试对数据 table 中的变量对重复一组线性回归。我有三个自变量 y1y2y3 和 10 个解释变量 x1x10。每个系列中都缺少一些观察结果。

在下面的示例中,我想为每对 ysxs 重复第二行命令。

d <- data.table(country=rep(c('a','b','c'),c(10,10,10)),y1=rnorm(30),y2=rnorm(30),x1=runif(30),x2=runif(30))

d[(!is.na(y1) & !is.na(x1)), .(beta1=summary(lm(y1~x1))$coefficients[2,1],    p1=summary(lm(y1~x1))$coefficients[2,4])  ,by=country]

这是一个更基本的方法。您可以使用 data.table::CJexpand.grid 生成 x 和 y 的组合。然后通过每个组合来执行线性回归。

combi <- CJ(grep("^x", names(d), value=TRUE),grep("^y", names(d), value=TRUE)) 

lmRes <- apply(combi, 1, function(x) {
    fml <- as.formula(paste(x["V2"],"~",x["V1"]))
    lm(fml, d)
})
lmRes

如果在连接这些组合之前无法从 d x 和 y 的所有组合生成大型数据集,可能没有更简单的方法可以通过连接表来解决此问题。