簡體   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