In the previous exercise, you saw how to code random-effect intercepts. You will now see how to code random-effect slopes. With lme4 syntax, lmer() uses (countinuous_predictor | random_effect_group) for a random-effect slope. When lme4 estimates a random-effect slope, it also estimates a random-effect intercept. scale() rescaled the predictor variable mathkind to make the model more numerically stable. Without this change, lmer() cannot fit the model. In the previous exercise, you estimated a random-effect intercept for each classroom and one slope for all data. Here, you will estimate a random-effect intercept for each class and a random-effect slope for each classroom. Like a random-effect intercept, a random-effect slope comes from a shared distribution of all random-effect slopes. # Rescale mathkind to make the model more stable student_data <- student_data %>% mutate(mathkind_scaled = scale(mathkind)) # Build lmer models lmer_intercept <- lmer(mathgain ~ mathkind_scaled + (1 | classid), data = student_data) lmer_slope <- lmer(mathgain ~ (mathkind_scaled | classid), data = student_data) # Add the predictions to the original data student_data_subset <- student_data %>% mutate(lmer_intercept = predict(lmer_intercept), lmer_slope = predict(lmer_slope)) %>% filter(schoolid == "1") # Plot the predicted values ggplot(student_data_subset, aes(x = mathkind_scaled, y = mathgain, color = classid)) + geom_point() + geom_line(aes(x = mathkind_scaled, y = lmer_intercept)) + geom_line(aes(x = mathkind_scaled, y = lmer_slope), linetype = 'dashed') + theme_bw() + scale_color_manual("Class ID", values = c("red", "blue")) The model with fixed-effect slopes has parallel lines (solid lines) because the slope estimates are the same. The model with random-effect slopes (dashed lines) does not have parallel lines because the slope estimates are different. The model with random-effect slopes (dashed lines) has lines that are shallower than the other model. This occurred because slopes are being estimated for each classroom, but include a shared distribution. This shared distribution pools information from all classrooms (including those not shown on the plot).