如何将字符串公式传递给 R 的 lm 并查看摘要中的公式? [英] How to pass string formula to R's lm and see the formula in the summary?

查看:65
本文介绍了如何将字符串公式传递给 R 的 lm 并查看摘要中的公式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的R会话中, summary(model)将公式显示为 model_str .如何使它显示为 mpg〜cyl + hp ,同时仍然能够通过字符串设置模型公式?

In the R session below, summary(model) shows the formula as model_str. How do I get it to show as mpg ~ cyl + hp while still being able to set the model formula via a string?

> 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 中的实际值).

Use do.call so that model_str gets evaluated before being sent to lm but quote mtcars so that it is not (otherwise there would be a huge output showing the actual values in 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  

这篇关于如何将字符串公式传递给 R 的 lm 并查看摘要中的公式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆