4

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?

Qaswed
  • 2,629
  • 4
  • 21
  • 38
  • 2
    I think this is likely a scoping issue, rather than time of evaluation, due to how with.mids is written. As an alternative , you could define the formula as a string , `model_formula – user20650 Sep 24 '17 at 15:52

1 Answers1

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))))
Qaswed
  • 2,629
  • 4
  • 21
  • 38
  • You know what aligns with your workflow, but it does seem suboptimal to define your model as a formula, convert it to a character, and then back to a formula. ps some answers [here](https://stackoverflow.com/questions/14671172/how-to-convert-r-formula-to-text) show issue with using `format` in this way. – user20650 Sep 24 '17 at 21:54
  • formula(format(...))) produces the following warning: Using formula(x) is deprecated when x is a character vector of length > 1. Consider formula(paste(x, collapse = " ")) instead. This did the trick but it is very wordy: formula(paste(format(model_formula),collapse=' '))) – Samuel Saari Apr 26 '21 at 11:50