This question just migrated from crossvalidated, as it is indeed more a programming question.
I have tried a lot of things (all kind of way to provide info to the newdata
-argument), from which I present some below. The summary: everything works with lme4
, but only the first works with nlme
.
The question:
I need to use nlme
rather than lme4
because I want to be able to account for heteroscedasticity. But for some reason, comparisons
in the marginaleffects
package keeps producing the same error, no matter what I try: Error: Unable to compute predicted values with this model. You can try to supply a different dataset to the newdata
argument.
Below some some toy-data that replicates the problem. Only the first comparison
-command works, the others all give the error-message.
base <- expand.grid(time = 0:5,
Treat = LETTERS[1:3], stringsAsFactors = FALSE)
base <- base%>%bind_rows(base, base)%>%group_by(time, Treat)%>%
mutate(repl = row_number(),
replicate = sprintf("%s-%s", Treat, repl))%>%ungroup()
re <- data.frame(replicate = unique(base$replicate),
re = rnorm(9))
datasim <- base%>%left_join(re)%>%
mutate(out = re + rnorm(54, sd = 1 + time))%>%
mutate(ctime = as.character(time))
fit <- nlme::lme(out ~ ctime*Treat,
random = ~ 1| replicate,
weights = varIdent(form = ~ 1 | ctime),
data = datasim)
comparisons(fit)
comparisons(fit,
variables = "Treat")
comparisons(fit,
variables = list(Treat = "pairwise"))
comparisons(fit,
variables = list(Treat = "reference"),
)
comparisons(fit,
variables = list(Treat = "pairwise"),
newdata = datagrid(ctime = "5"))
comparisons(fit,
variables = list(Treat = "pairwise"),
newdata = datagrid(ctime = "5", model = fit))
comparisons(fit,
variables = list(Treat = "pairwise"),
newdata = datagrid(ctime = "5", replicate = "A-1"))
If I replace the lme
-call by an lmer
-call, all of the comparisons run as they should.
Convert the
Treat
variable to a factor before fitting your model.This is (arguably) an upstream problem with the handling of character variables in
predict.lme()
, which breaks whennewdata
does not include all levels of the predictor.Load packages and prep data:
Fit model and comparisons: