rnorouzian
rnorouzian

Reputation: 7517

predict() in lmer not recognizing id variable

Following this tutorial, I want to use predict() so that I can pop in unique values of all my predictors and then get the predicted values for those unique values.

But I keep getting strange errors (see below). Is there possibly a fix to this?

library(lme4)

dat3 <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/dat3.csv')

m4 <- lmer(math~pc1+pc2+discon+(pc1+pc2+discon|id), data=dat3)

newdata <- with(dat3, expand.grid(pc1=unique(pc1), pc2=unique(pc2), discon=unique(discon)))

predict(m4, newdata=newdata)

#### ERROR:
Error in model.frame.default(tt, newdata.NA, na.action = na.pass, xlev = orig.random.levs) : 
  invalid type (closure) for variable 'id'

enter image description here

Upvotes: 0

Views: 404

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226047

You haven't specified a value for the random effects in your prediction data frame. To get population-level predictions (ignoring the random effects), use

predict(m4, newdata=newdata, re.form=NA)

You're getting a weird error message because you have a package loaded (probably dplyr) which has an id() function defined: if you didn't, you would get the more interpretable error message

Error in eval(predvars, data, env) : object 'id' not found

Upvotes: 1

Related Questions