How to pass string formula to R's lm and see the formula in the summary?

泪湿孤枕 提交于 2020-12-13 03:50:47

问题


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

回答1:


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)))

giving:

Call:
lm(formula = mpg ~ cyl + hp, data = mtcars)

Coefficients:
(Intercept)          cyl           hp  
   36.90833     -2.26469     -0.01912  



回答2:


It's a bit of a hack and so probably fragile, but modifying the formula element of the call element of the model works:

model$call$formula <- formula(model_str)
summary(model)
## Call:
## lm(formula = mpg ~ cyl + hp, data = mtcars)



回答3:


You can build and evaluate the call directly in a single line:

eval(as.call(list(quote(lm), formula = model_str, data = quote(mtcars))))
#> 
#> Call:
#> lm(formula = "mpg ~ cyl + hp", data = mtcars)
#> 
#> Coefficients:
#> (Intercept)          cyl           hp  
#>    36.90833     -2.26469     -0.01912  



回答4:


Use str2lang, then do.call.

fo <- str2lang("mpg ~ hp + am")
do.call("lm", list(fo, quote(mtcars)))
# 
# Call:
#   lm(formula = mpg ~ hp + am, data = mtcars)
# 
# Coefficients:
# (Intercept)           hp           am  
#    26.58491     -0.05889      5.27709  


来源:https://stackoverflow.com/questions/64487754/how-to-pass-string-formula-to-rs-lm-and-see-the-formula-in-the-summary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!