Mixed models with nested random effects in R

Once again, SPSS failed me miserably while trying to run my mixed, multilevel model below:

nested model

The first two levels, BSO(i.e. day care center) and pp (participant) are nested random effects. As the model shows, each participant’s “emotional” or behavioral code (e.g. engaged, excited, bored, …) was sampled several times, during two sessions (once for each of the app’s two versions). SPSS failed to allow me to build this model properly, mostly failing to comprehend that random effects have more than one level.

So I turned to R and found several, very interesting (though maybe a bit long to read) tutorials using the package lme4, so credit goes to Bodo and Ben for their extensive effort into simplifying what could be a very complex process.

The way it worked for me is below, described in an overly simplified way.

require(xlsx) #to read excel sheets
require(lme4) #the package
Behavioral <- read.xlsx("behavioral", 1) #the data set

#certain things we need to ensure are treated as factors
#default is covariants
Behavioral$version = as.factor(Behavioral$version)
Behavioral$pp = as.factor(Behavioral$pp)

#first we construct the null model
#emotion type as response with no fixed factors
#and a nested BSO and pp as random factors
model.null <-lmer(emo.type ~ 1 + 1|BSO/pp, data = Behavioral, REML=FALSE)

#we then construct our model, adding version as fixed factor
model <-lmer(emo.type ~ version + 1|BSO/pp, data = Behavioral, REML=FALSE)

#see summaries of the models here
summary (model.null)
summary (model)

#to obtain the p-value, i.e. to see if adding
#the fixed factor made a significant difference
anova(model.null,model)

#and finally
citation("lme4")
#will generate a bibtex entry so you cite the authors of the package!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s