I am trying to fit a mixed model into different datasets with different sets of variables, so I need to buffer the formula having defined it previously using the as.formula()
.
formula = as.formula(paste(paste(max_age_outcome, "~"), paste(independent_vars, collapse = " + "), paste0("+ (1|", evaluator_var, ")")))
gc ~ sex + medu + fedu + mses + fses + parity + mage + fage + smok + (1 | gc_eval)
After this, when I do the multiple modeling to each simulation generated by the MICE package, if I buffer the formula using this previously defined I get this error:
fit_list <- with(imputed_data, lmer(formula = formula))
Error in eval(predvars, data, env) : object 'sex' not found
However, If I directly pass the variables by writing there is no problem:
with(imputed_data, lmer(formula = gc ~ sex + medu + fedu + mses + parity + mage + smok + (1 | gc_eval)))
Does someone has any idea on why this is happening and how to solve it? I'm completely stuck...
Tryin moving the creation of the formula into the with()
block
fit_list <- with(imputed_data, {
formula <- as.formula(paste(paste(max_age_outcome, "~"),
paste(independent_vars, collapse = " + "),
paste0("+ (1|", evaluator_var, ")")))
lmer(formula = formula)
})
The issue is that formulas capture the environment where they are created. And since you are not passing data=
to the modeling function, it will look for the values of the variables in the environment where the formula was created. But the values you want to use are not created outside the with()
call so you need to create the formula inside.