Multilevel Models

Multilevel models are assembled in the package lme4 which has to be invoked (loaded) prior to model estimation. Lest it be forgotten, I add a statement to this effect to each example, even though the package has to be loaded only once during a session, of course.

Multilevel regression with a normal (metric) dependent variable

A random intercept model

library(lme4)
nmul1 <- lmer(success ~ depvar1 + depvar2 + depvar3 + (1 | groupid))

This version of the command implies that the variables under investigation are available as vectors in the current environment. Otherwise, a "data" option is required, or some other way of relating variables to a data set or matrix.

Multilevel logistic regression

A random intercept model

library(lme4)
mlmlog1 <- glmer(success ~ depvar1 + depvar2 + depvar3 + (1 | groupid), data=mydataframe,
   control = glmerControl(optimizer = "bobyqa"), nAGQ = 10)

The variable groupid is supposed to indicate the higher-level units to which the individual cases belong. The final two options (control ... and nAGQ ... refer to the algorithm used in the estimation. The control ... statement suppresses a warning of nonconvergence that is often issued but has no substantial meaning in most cases, and the nAGQ ... statement gives the number of integration points for the Gaussian Hermite approximation (the number should not be too large).

A random slope model

library(lme4)
mlmlog1 <- glmer(success ~ depvar1 + depvar2 + depvar3 + (1 + depvar1 | groupid),
   data=mydataframe, control = glmerControl(optimizer = "bobyqa"), nAGQ = 10)

depvar1 obviously is a lower-level variable here.

© W. Ludwig-Mayerhofer, R Guide | Last update: 19 Sep 2016