locus
locus

Reputation: 431

error with predict function with lmer object

I'm trying to reproduce the plot from Roland's code with lmer instead of nlme model but I'm getting an error with the predict function:

library(nlme)
library(lme4)
library(ggplot2)

fm2 <- lmer(distance ~ age + Sex + (1|Subject), data = Orthodont)

newdat <- expand.grid(Sex=unique(Orthodont$Sex),
                  age=c(min(Orthodont$age),
                            max(Orthodont$age)))

p <- ggplot(Orthodont, aes(x=age, y=distance, colour=Sex)) +
  geom_point(size=3) +
  geom_line(aes(y=predict(fm2), group=Subject, size="Subjects")) +
  geom_line(data=newdat, aes(y=predict(fm2, level=0, newdata=newdat), size="Population")) +
  scale_size_manual(name="Predictions", values=c("Subjects"=0.5, "Population"=3)) +
  theme_bw(base_size=22)

This is the error I get:

Error in eval(predvars, data, env) : object 'Subject' not found
In addition: Warning message:
In predict.merMod(fm2, level = 0, newdata = newdat) :
  unused arguments ignored

Upvotes: 0

Views: 562

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226761

If you want to plot subject-level predictions, you would need to include Subject in your prediction frame:

pframe <- with(Orthodont,
  expand.grid(Sex=unique($Sex),
              age=range(age),
              Subject=unique(Subject))
)

Alternately you could include re.form = ~0 in your predict call: this is equivalent to the (ignored!) level=0 specification in your current code, which only works for lme ...

Upvotes: 3

Related Questions