首页 文章

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

提问于
浏览
1

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

例如,我想创建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

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

1 回答

  • 1

    这是一个不太通用的方法,但是如果你在 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
    

    Edit 基于@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
    

相关问题