Quantcast
Channel: Active questions tagged lm - Stack Overflow
Viewing all articles
Browse latest Browse all 124

R - how to pass a formula to a with(data, lm(y ~ x)) construction

$
0
0

This question is highly related to R - how to pass formula to a with(df, glm(y ~ x)) construction inside a function but asks a broader question.

Why do these expressions work?

text_obj <- "mpg ~ cyl"form_obj <- as.formula(text_obj)with(mtcars, lm(mpg ~ cyl)) with(mtcars, lm(as.formula(text_obj))) lm(form_obj, data = mtcars)

But not this one?

with(mtcars, lm(form_obj))Error in eval(predvars, data, env) : object 'mpg' not found

I would usually use the data argument but this is not possible in the mice package.Ie.

library(mice)mtcars[5, 5] <- NA # introduce a missing value to be imputedmtcars.imp = mice(mtcars, m = 5)

These don't work

lm(form_obj, data = mtcars.imp)with(mtcars.imp, lm(form.obj))

but this does

with(mtcars.imp, lm(as.formula(text_obj)))

Thus, is it better to always thus use the as.formula argument inside the function, rather than construct it first and then pass it in?


Viewing all articles
Browse latest Browse all 124

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>