Random-effect intercepts
Linear models in R estimate parameters that are considered fixed or non-random and are called fixed-effects. In contrast, random-effect parameters assume data share a common error distribution, and can produce different estimates when there are small amounts of data or outliers. Models with both fixed and random-effects are mixed-effect models or linear mixed-effect regression.
The lme4
package fits mixed-effect models (models with both fixed- and random-effects) with lmer()
, which uses a formula similar to lm()
.But, random-effect intercepts use special syntax:
lmer(y ~ x + (1 | random-effect), data = my_data)
lmer()
function requires the model to include a random-effect, otherwise the model gives you an error. Here, you will fit a lm()
and a lmer()
, and then graphically compare the fitted models using a subset of the data. We provide this code because of the advanced data wrangling, which is required because random-effects are usually not plotted (ggplot2
also does not include nice plot options for mixed-effect models). In this plot, notice how the dashed lines from random-effect slopes compare to the solid lines from the fixed-effect slopes.
Note: broom.mixed
is required because the broom
package does not support lme4
.
This exercise is part of the course
Hierarchical and Mixed Effects Models in R
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Build a liner model including class as fixed-effect model
lm_out <- ___
# Build a mixed-effect model including class id as a random-effect
lmer_out <- lmer(___ ~ ___ + (1 | ___), data = ___)
# Extract out the slope estimate for mathkind
tidy(lm_out) %>%
filter(term == "mathkind")
tidy(lmer_out) %>%
filter(term == "mathkind")