1. Learn
  2. /
  3. Courses
  4. /
  5. Hierarchical and Mixed Effects Models in R

Connected

Exercise

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.

Instructions 1/3

undefined XP
    1
    2
    3
  • Build a linear model with mathgain predicted by classid + mathkind using the student_data. Save the output as lm_out.
  • Build a linear mixed-effect model with mathgain predicted by mathkind as a fixed-effect and classid predicted as a random-effect using the student_data.
  • Run the existing code to extract out the mathkind coefficient details.