Running mice with a formula as a variable: instant evaluation instead of later evaluation?

三世轮回 提交于 2020-02-24 11:26:47

问题


The R package micecomes 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

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