繁体   English   中英

R 多重回归循环和提取系数

[英]R Multiple Regression Loop and Extract Coefficients

我必须对同一自变量矩阵上的许多因变量向量执行多元线性回归。

例如,我想创建 3 个模型,以便:

lm( d ~ a + b + c )
lm( e ~ a + b + c )
lm( f ~ a + b + c )

来自以下矩阵(a、b、c 是自变量,d、e、f 是因变量)

       [,1]     [,2]     [,3]     [,4]     [,5]     [,6]
[1,]    a1       b1       c1       d1       e1       f1
[2,]    a2       b2       c2       d2       e2       f2
[3,]    a3       b3       c3       d3       e3       f3

然后我想将回归的系数存储在另一个矩阵中(为了便于解释,我在示例中减少了列数和向量数)。

这是一个不是很通用的方法,但如果您在depvar替换您自己的因变量名称,当然还有内部lm()调用中所有模型共有的自变量,当然还有数据集名称。 在这里,我在mtcars上进行了mtcars ,这是一个随 R 提供的内置数据集。

depvar <- c("mpg", "disp", "qsec")
regresults <- lapply(depvar, function(dv) {
    tmplm <- lm(get(dv) ~ cyl + hp + wt, data = mtcars)
    coef(tmplm)
})
# returns a list, where each element is a vector of coefficients
# do.call(rbind, ) will paste them together
allresults <- data.frame(depvar = depvar, 
                         do.call(rbind, regresults))
# tidy up name of intercept variable
names(allresults)[2] <- "intercept"
allresults
##   depvar  intercept        cyl          hp        wt
## 1    mpg   38.75179 -0.9416168 -0.01803810 -3.166973
## 2   disp -179.04186 30.3212049  0.21555502 59.222023
## 3   qsec   19.76879 -0.5825700 -0.01881199  1.381334

根据@Mike Wise 的建议进行编辑

如果您只想要一个数字数据集但想要保留标识符,您可以将其添加为 row.name,如下所示:

allresults <- data.frame(do.call(rbind, regresults),
                         row.names = depvar)
# tidy up name of intercept variable
names(allresults)[1] <- "intercept"
allresults
##       intercept        cyl          hp        wt
## mpg    38.75179 -0.9416168 -0.01803810 -3.166973
## disp -179.04186 30.3212049  0.21555502 59.222023
## qsec   19.76879 -0.5825700 -0.01881199  1.381334

我实际上最近遇到了同样的问题,一种快速简便的方法是简单地手动将所有结果添加到具有系数函数的数据帧中。

coeffdf <- data.frame(coefficients(lm1),coefficients(lm2))

如果每个回归都有相同的变量,它会工作得很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM