Extend random-intercept LMMs by adding random slopes, enabling individualized change trajectories and richer inferences for ABCD longitudinal outcomes.
Work in ProgressExamples are a work in progress. Please exercise caution when using code examples, as they may not be fully verified. If you spot gaps, errors, or have suggestions, we'd love your feedback—use the "Suggest changes" button to help us improve!
Overview
Linear Mixed Models with random slopes allow each individual to have a unique trajectory of change over time, recognizing heterogeneous developmental patterns across participants. By estimating both random intercepts and random slopes, this approach captures individual differences in baseline levels and rates of change, providing more accurate representations than models assuming identical trajectories. This tutorial demonstrates random slope LMM using cognitive data from ABCD youth across four assessments, modeling individual differences in baseline cognition and change rates to capture both population-level trends and participant-specific deviations.
When to Use:
Choose this approach when both baselines and rates of change vary across participants—typical in ABCD longitudinal cognition or behavioral measures.
Key Advantage:
Random slopes capture heterogeneous growth rates, improving prediction accuracy and highlighting how change differs across individuals.
What You'll Learn:
How to specify random intercept + slope structures in , interpret intercept-slope covariance, and plot individual trajectories.
Data Access
Data Download
ABCD data can be accessed through the DEAP platform or the NBDC Data Access Platform (LASSO), which provide user-friendly interfaces for creating custom datasets with point-and-click variable selection. For detailed instructions on accessing and downloading ABCD data, see the DEAP documentation.
Loading Data with NBDCtools
Once you have downloaded ABCD data files, the NBDCtools package provides efficient tools for loading and preparing your data for analysis. The package handles common data management tasks including:
Automatic data joining - Merges variables from multiple tables automatically
Built-in transformations - Converts categorical variables to factors, handles missing data codes, and adds variable labels
Event filtering - Easily selects specific assessment waves
### Fit a Linear Mixed Model (LMM) with random intercepts and slopes
model <- lmerTest::lmer(
cognition ~ time + (1 + time | participant_id), # Fixed effect (time), random intercept & slope (participant_id)
data = df_long # Dataset containing repeated measures of cognition
)
### Generate a summary table for the LMM model (gtsummary format)
model_summary_table <- gtsummary::tbl_regression(model,
digits = 3,
intercept = TRUE
) %>%
gtsummary::as_gt()
### Save the gt table
gt::gtsave(
data = model_summary_table,
filename = "model_summary.html",
inline_css = FALSE
)
# Generate an alternative summary table with random effects (sjPlot format)
# This provides additional details on variance components not shown in gtsummary
sjPlot::tab_model(model,
show.se = TRUE, show.df = FALSE, show.ci = FALSE,
digits = 3,
pred.labels = c("Intercept", "Time"), # Adjust predictor labels
dv.labels = c("Random Intercept & Slope LMM"), # Update model label
string.se = "SE",
string.p = "P-Value",
file = "lmm_model_results.html"
)
Characteristic
Beta
95% CI
p-value
(Intercept)
51
50, 51
<0.001
time
-0.19
-0.23, -0.14
<0.001
Abbreviation: CI = Confidence Interval
Random Intercept & Slope LMM
Predictors
Estimates
SE
P-Value
Intercept
50.545
0.117
<0.001
Time
-0.188
0.023
<0.001
Random Effects
σ2
34.47
τ00participant_id
89.96
τ11participant_id.time
0.56
ρ01participant_id
-0.29
ICC
0.71
N participant_id
8666
Observations
21256
Marginal R2 / Conditional R2
0.001 / 0.715
Interpretation
Interpretation
The fixed effects estimates suggest that the average cognition score at baseline (time = 0) is 50.545 (SE = 0.117, p < 0.001), with cognition declining by 0.188 points per biannual assessment (SE = 0.023, p < 0.001).Examining the random effects, we find considerable variability in both baseline cognition scores (random intercept variance τ₀₀ = 89.96) and individual rates of cognitive decline (random slope variance τ₁₁ = 0.56). The negative correlation (ρ₀₁ = -0.29) between the intercept and slope suggests that individuals with higher initial cognition scores tend to experience steeper declines over time. This model better accounts for individual differences in both starting cognition levels and their rate of change, making it a more flexible approach compared to the random-intercept-only model.
Generate Quick Diagnostic Plot and Predictions
29 lines
# Generate quick diagnostic plot using sjPlot
sjPlot::plot_model(model,
type = "pred",
terms = c("time"),
title = "Predicted Cognition Scores Over Time",
axis.title = c("Time", "Predicted Cognition"),
show.data = TRUE,
ci.lvl = 0.95,
dot.size = 2,
line.size = 1.2,
jitter = 0.2,
file = "lmm_sjPlot_results.html"
)
# Generate model predictions for custom visualization
df_long <- df_long %>%
mutate(
predicted_fixed = predict(model, re.form = NA),
predicted_random = predict(model, re.form = ~ (1 + time | participant_id))
)
# Select a subset of participant IDs for visualization
set.seed(124)
sample_ids <- sample(unique(df_long$participant_id),
size = min(250, length(unique(df_long$participant_id))))
# Filter dataset to include only sampled participants
df_long_sub <- df_long %>%
filter(participant_id %in% sample_ids)
Create Custom Trajectory Visualization
45 lines
# Create the visualization of individual and overall cognition trajectories
visualization <- ggplot(df_long_sub, aes(x = time, y = cognition, group = participant_id)) +
# Plot observed data (individual trajectories)
geom_line(aes(color = "Observed Data"), alpha = 0.3) +
geom_point(alpha = 0.3) +
# Plot model-predicted values with random intercepts and slopes
geom_line(aes(y = predicted_random, color = "Model Predictions"), alpha = 0.7) +
geom_line(aes(y = predicted_fixed, group = 1, color = "Population Mean"), linewidth = 1.2) +
# Customize colors for clarity
scale_color_manual(values = c(
"Observed Data" = "red",
"Model Predictions" = "grey40",
"Population Mean" = "blue"
)) +
# Format x-axis labels
scale_x_continuous(
breaks = 0:3,
labels = c("Baseline", "Year 2", "Year 4", "Year 6")
) +
# Add labels and title
labs(
title = "Random Intercept-Slope Model: Individual Trajectories",
x = "Assessment Wave",
y = "Cognition",
color = "Trajectory Type"
) +
# Apply theme
theme_minimal() +
theme(legend.position = "bottom")
# Display the plot
visualization
# Save the plot
ggsave(
filename = "visualization.png",
plot = visualization,
width = 8, height = 6, dpi = 300
)
Interpretation
Interpretation
The plot illustrates individual and overall cognition trajectories over time. Red lines represent observed cognition trajectories for each participant, while grey lines depict their model-estimated trajectories incorporating both random intercepts and random slopes. The blue line represents the overall fixed-effect mean trajectory, summarizing the population-average trend in cognition from Baseline to Year 6.Compared to the random intercept-only model, the random slopes component allows for individual differences in the rate of cognitive change over time. This results in diverging trajectories, where some individuals experience steeper declines while others remain relatively stable. The negative intercept-slope correlation (-0.29) suggests that those with higher initial cognition tend to decline faster, a pattern captured by the spread of grey lines becoming wider over time.
Discussion
The random-slope LMM revealed substantial heterogeneity in cognitive trajectories despite an average decline of 0.188 points per biennial assessment. Random intercept variance (τ₀₀ = 89.96) indicated wide dispersion in baseline cognition, and slope variance (τ₁₁ = 0.56) showed that participants diverged in how quickly they changed. Together, these estimates justify the added complexity of allowing participant-specific slopes instead of forcing one common trajectory.
The negative intercept–slope correlation (ρ₀₁ = −0.29) suggested regression-to-the-mean dynamics: children who started high tended to drop faster, whereas lower-performing peers often declined slowly or even stabilized. Residual diagnostics showed no major violations of normality or homoscedasticity, and the conditional R² improved noticeably relative to a random-intercept-only model. Practically, these findings emphasize that interventions targeting cognitive decline should be personalized, because youth begin at different levels and respond differently over time even when exposed to the same macro-level experiences.
Additional Resources
4
lme4 Package Documentation
DOCS
Official CRAN documentation for the lme4 package, with detailed coverage of random slopes models using the (1 + time|subject) syntax. Explains variance-covariance matrix estimation for random effects and interpretation of intercept-slope correlations.
Comprehensive guide to linear mixed-effects modeling with lme4, including random slopes specification, convergence troubleshooting, and diagnostic procedures. Section 2.3 specifically addresses modeling individual differences in change trajectories with correlated random effects.
Data Analysis Using Regression and Multilevel Models
BOOK
Gelman & Hill (2007). Chapters 11-13 cover varying-intercept and varying-slope models with excellent practical guidance on model building, interpretation of random effects correlations, and when to include random slopes. Includes discussion of the bias-variance tradeoff in complex random effects structures.
R package providing publication-ready tables and plots for lme4 models, including plot_model() for visualizing random slopes and tab_model() for formatted regression tables with variance components. Particularly useful for showing individual trajectories with confidence bands.