r - 如何将字符串公式传递给 R 的 lm 并在摘要中查看公式?
问题描述
在下面的 R 会话中,summary(model)
公式显示为model_str
。如何让它显示为mpg ~ cyl + hp
同时仍然能够通过字符串设置模型公式?
> data(mtcars)
> names(mtcars)
[1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb"
> model_str <- 'mpg ~ cyl + hp'
> model <- lm(model_str, data=mtcars)
> summary(model)
Call:
lm(formula = model_str, data = mtcars)
Residuals:
Min 1Q Median 3Q Max
-4.4948 -2.4901 -0.1828 1.9777 7.2934
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 36.90833 2.19080 16.847 < 2e-16 ***
cyl -2.26469 0.57589 -3.933 0.00048 ***
hp -0.01912 0.01500 -1.275 0.21253
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 3.173 on 29 degrees of freedom
Multiple R-squared: 0.7407, Adjusted R-squared: 0.7228
F-statistic: 41.42 on 2 and 29 DF, p-value: 3.162e-09
解决方案
使用do.call
以便model_str
在发送到之前进行评估,lm
但引用mtcars
以便它不是(否则会有一个巨大的输出显示实际值mtcars
)。
do.call("lm", list(as.formula(model_str), data = quote(mtcars)))
给予:
Call:
lm(formula = mpg ~ cyl + hp, data = mtcars)
Coefficients:
(Intercept) cyl hp
36.90833 -2.26469 -0.01912
推荐阅读
- html - Bootstrap 4卡页脚填充列的剩余高度
- apache-spark - RDD中用户定义的哈希分区与键
- python - 如何在 Python 上使用 map 和 set
- filter - 防止加载有 100 万成员的过滤器
- c# - 如何将捐赠金额添加到我的数据库
- spring - 将可分页对象和搜索参数发送到 Spring Boot 端点
- ios - 输出视频比录制的预览视频短
- dependency-injection - 在 AutoFac 中,为什么我的通用存储库的 RegisterGeneric 调用顺序仅适用于最后一个注册的存储库?
- c# - c# 使用 Microsoft Interop 对 Excel 中的行进行排序
- flutter - Flutter 仅调试打开/特定文件(Android Studio)