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

标签 r for-loop extract coefficients multiple-regression

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

例如,我想创建 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 上进行了演示,这是一个随 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

关于R 多元回归循环和提取系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31378793/

相关文章:

wpf - 提取正在运行的WPF应用程序的WPF内容模板

regex - bash:正则表达式提取

r - mlr 包 : Cross-validation with tuneParams() and resample() yield different results

r - Shiny :如何在通过 actionButton 评估输入条件时更改输出(视觉数据到警告消息,反之亦然)

python - 循环遍历 df 字典以合并 Pandas 中的 df

javascript - 为了提高循环效率,将两个 for 循环合为一个

nlp - 从社交文件中提取用户兴趣

从 R 中的 CSV 文件读取 xts

css - Shiny - 更改文本(框)的大小、颜色和字体

matlab - 是否可以根据用户输入禁用 'for' 循环?