Linear Mixed Models from Scratch: A Hands-on Course

Learning by doing with R + lme4

Published

October 17, 2026

Introduction

English version — machine-assisted translation (by generative AI, Anthropic Claude) of the original Japanese hands-on. 日本語版はこちら.

This hands-on is a course for understanding linear mixed models (LMMs) from scratch, while running code yourself.

Who this is for

  • Readers with introductory statistics knowledge
    • You have an intuitive sense of mean, variance, standard deviation, scatter plots, correlation, and simple regression
    • You have heard of p-values and confidence intervals
  • Readers who have used R at least a little (even if you have never used it, you can follow along by copying and running the code)

There are some equations, but each one is always explained in the order “equation → picture → code”. Even if the equations are unclear, it is fine as long as the pictures and the code output make sense to you.

What you will be able to do

  1. Explain why ordinary regression is not appropriate in some situations
  2. Explain in your own words what fixed effects and random effects mean
  3. Fit random-intercept and random-slope models with lme4::lmer() and read the output
  4. Compare and diagnose models, and report the results

Chapters

Chapter Content Approx. time
1 Why linear mixed models are needed 20 min
2 Review of simple regression 15 min
3 Three kinds of pooling 25 min
4 Random-intercept models 30 min
5 Random-slope models 30 min
6 Tests and model comparison 25 min
7 Diagnostics and reporting 20 min
8 Exercises 40 min
NoteSlides

Summary slides for study groups and lectures are here. Press F for full screen, S for speaker notes, and Esc for the overview.

Setup

We use R (4.1 or later) and the following packages.

install.packages(c("lme4", "lmerTest", "ggplot2"))
  • lme4: the standard package for linear mixed models. We use the lmer() function
  • lmerTest: adds p-values to lmer() results
  • ggplot2: plotting

At the top of each chapter we load the common setup file R/setup.R. It only loads the packages and defines sim_school(), a function that creates practice data.

source("R/setup.R")
TipHow to work through this

You can copy each code block with the button at its top right. Paste it into RStudio or similar and read on while running it yourself. Changing the numbers and seeing how the results change is the fastest way to learn.

Building and deploying this site

./build.sh             # build the book + slides into _book/
quarto preview         # preview the book locally

Because freeze: auto is set in _quarto.yml, computation results are stored in _freeze/. Only the static files in _book/ need to be deployed; no R or Python is needed on the server. See README.md in the repository for details.