I'm trying to use a dynamic covariate (taken from user input) in an lmer model. This works fine, but applying emmeans doesn't work any longer.


fit1 = lmer(get(uservar) ~ Intervention + period + sequence + age + (1|ID),
            data = mydata, REML=T)


emmeans(fit1, list(pairwise ~ Intervention), adjust = "tukey")

are running without problems.

lmer(get(uservar) ~ Intervention + period + sequence + get(covariable) + (1|ID),
     data = mydata, REML=T)

with covariable being "age" taken from a user input pop-up box also works.


emmeans(fit1, list(pairwise ~ Intervention), adjust = "tukey")

does not run any longer. It's saying:

variables have different lengths (found for 'covariable')

But that's not true. If I check mydata[,covariable] it has got the same length as the other variables.

Any suggestions what to do?

2 Answers

rvl On

emmeans() has to be able to reconstruct the data for the predictor variables to get things like the means of the covariates and levels of the factors. It will work if you save the user-specified data in a data frame and fit the model using that data frame. But keep in mind that if you subsequently change that data frame, say with another user input, it will change the emmeans() results even if you don’t refit the model, because it has no way of knowing that the data changed.

Community On

I've found a very simple solution:

fixed.part <- "get(usevar) ~ Intervention + Periode + Sequenz +  (1|ID)"
random.part <- covariable

fit1 <- lmer(formula(paste(fixed.part, random.part, sep = " + ")), 
 data =testdat_long_cc, REML=TRUE)