I am looping over about 20 columns, running mixed models. That all works fine. But when I try to calculate emmeans, I get an error because of the get(thisvar)
in the model. The code is:
for(thisvar in thesevars){
mod_linear <- lmer(edss ~ time + get(thisvar) + age + gender + relapse_prior_1yr + new_lesions_prior_1yr + weight + (1|id), data = dat_long)
emms_mod_linear <- emmeans(mod_linear, ~ time, at = list(time = seq(0, 12, 1)))
}
and the error is:
Error in (function (object, at, cov.reduce = mean, cov.keep = get_emm_option("cov.keep"), :
We are unable to reconstruct the data.
The variables needed are:
time thisvar age gender relapse_prior_1yr new_lesions_prior_1yr weight
Are any of these actually constants? (specify via 'params = ')
The dataset name is:
dat_long
Does the data still exist? Or you can specify a dataset via 'data = '
How can I use emmeans in a loop with get()? Thanks
A fix for your issue would be to get rid of get()
and instead use e.g. reformulate
to create the formula
object in your loop.
Using a minimal reproducible example based on mtcars
and using lm
:
library(emmeans)
thisvars <- c("hp", "cyl")
emms_mod_linear <- list()
for (thisvar in thisvars) {
fml <- reformulate(c("am", thisvar), response = "mpg")
mod_linear <- lm(fml, data = mtcars)
emms_mod_linear[[thisvar]] <- emmeans(mod_linear, ~am, at = list(am = c(0, 1, 2)))
}
emms_mod_linear
#> $hp
#> am emmean SE df lower.CL upper.CL
#> 0 17.9 0.676 29 16.6 19.3
#> 1 23.2 0.822 29 21.5 24.9
#> 2 28.5 1.796 29 24.8 32.2
#>
#> Confidence level used: 0.95
#>
#> $cyl
#> am emmean SE df lower.CL upper.CL
#> 0 19.0 0.753 29 17.5 20.6
#> 1 21.6 0.938 29 19.7 23.5
#> 2 24.2 2.128 29 19.8 28.5
#>
#> Confidence level used: 0.95