![](/img/trans.png)
[英]How to keep a variable in fit$model for lm() in R that I'm *not* using within the lm call itself?
[英]Using lapply to fit multiple model — how to keep the model formula self-contained in lm object
以下代碼使用 for 循環或 lapply 將 4 個不同的模型公式擬合到mtcars
數據集。 在這兩種情況下,存儲在結果中的formulas[[1]]
被稱為formulas[[1]]
、 formulas[[2]]
等,而不是人類可讀的公式。
formulas <- list(
mpg ~ disp,
mpg ~ I(1 / disp),
mpg ~ disp + wt,
mpg ~ I(1 / disp) + wt
)
res <- vector("list", length=length(formulas))
for (i in seq_along(formulas)) {
res[[i]] <- lm(formulas[[i]], data=mtcars)
}
res
lapply(formulas, lm, data=mtcars)
有沒有辦法讓完整的、可讀的公式顯示在結果中?
這應該工作
lapply(formulas, function(x, data) eval(bquote(lm(.(x),data))), data=mtcars)
它會重新運行
[[1]]
Call:
lm(formula = mpg ~ disp, data = data)
Coefficients:
(Intercept) disp
29.59985 -0.04122
[[2]]
Call:
lm(formula = mpg ~ I(1/disp), data = data)
Coefficients:
(Intercept) I(1/disp)
10.75 1557.67
....etc
我們使用bquote
將公式插入到對lm
的調用中,然后對表達式求值。
為什么不只是:
lapply( formulas, function(frm) lm( frm, data=mtcars))
#------------------
[[1]]
Call:
lm(formula = frm, data = mtcars)
Coefficients:
(Intercept) disp
29.59985 -0.04122
[[2]]
Call:
lm(formula = frm, data = mtcars)
Coefficients:
(Intercept) I(1/disp)
10.75 1557.67
snpped....
如果您希望結果的名稱具有公式的“字符”化版本,那就是“
names(res) <- as.character(formulas)
res[1]
#-----
$`mpg ~ disp`
Call:
lm(formula = frm, data = mtcars)
Coefficients:
(Intercept) disp
29.59985 -0.04122
你也可以嘗試類似的東西
library(purrr)
library(tibble)
models <- map(formulas, lm, data = mtcars)
models
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.