问题
The R
package mice
comes with following example:
library("mice")
imp <- mice(nhanes)
fit <- with(data=imp,exp=lm(bmi~hyp+chl))
I want a flexible call of with()
like:
model_formula <- bmi~hyp+chl
fit <- with(data=imp,exp=lm(model_formula))
But this throws Error in eval(predvars, data, env) : object 'bmi' not found
. I searched for similar problems. The closet problem I found was Help understand the error in a function I defined in R.
My impression is, that writing exp=lm(model_formula)
the expression lm(model_formula)
is evaluted instantly, but when writing exp = lm(bmi~hyp+chl)
it is not evaluated straight away - instead the eavluation will take place in the function with.mice()
? And if so, how can I prevent instant evaluation?
回答1:
The comment by @user20650 was the clue to the solution. It is needed to change the formula first to a character, which will be achieved by format
, and made it then a formula again:
model_formula <- bmi~hyp+chl
fit <- with(data=imp,exp=lm(formula(format(model_formula))))
来源:https://stackoverflow.com/questions/46391618/running-mice-with-a-formula-as-a-variable-instant-evaluation-instead-of-later-e