Workshop
Mixed models in R
Nathan A. Baune, PhD · first given 29 September 2026 · about 30 minutes
Why, how, and the pitfalls that catch ANOVA-trained eyes.
Why mixed models, random intercepts and slopes, and the common pitfalls: reference levels, emmeans, df, CIs, power, plots.
Everything here is yours to study and reuse afterwards: this page, its source, and the Claude Code skill that built it are at
gitlab.com/neurotrophy-git/presentations.
This page is also the handout. The code, asides and sources stay here. Press P for a full-screen view.
Mixed models
MLM (multilevel model), HLM (hierarchical linear model), LMM (linear mixed model), LMEM (linear mixed-effects model) and MEM (mixed-effects model) are one family. HLM is the education and psychology name; LMM and LMEM are the statistics names. GLMM (generalized linear mixed model, also written GLMEM) is the version for outcomes that aren't normally distributed, such as binary (fall / no fall) or counts.
Why mixed models
Our data are nested
Trials from one person are more alike than trials from two different people. That similarity is structure, not noise.
Any analysis has to decide what to do with it. Ignoring it and averaging it away are both choices, and both cost something.
Quick check: how many trials per participant does your current study have? Keep that number in mind for the next few sections.
Why mixed models
The usual approach: average first, then test
Aggregate, then t-test, LM or ANOVA
Standard practice: average each participant down to one number per condition, then compare those means. It is valid, but it throws information away:
- Trial-to-trial variability is gone.
- A mean from 8 usable trials counts the same as one from 40.
- Trial-level predictors (trial number, step width, fatigue) can't enter the model.
- An unpaired test or LM on those means ignores that the same person appears in every condition.
Repeated-measures ANOVA on those means
The most common version. It handles the pairing, but it needs complete cells (one missing condition drops the whole participant), sphericity corrections, and cannot take continuous predictors cleanly.
Rarer, but it happens: lm() on every raw trial. That treats 40 trials from one person as 40 people (pseudoreplication), so SEs shrink and false positives climb.
The bridge for ANOVA people: with balanced, complete data, a random-intercept model gives the same answer as RM-ANOVA under compound symmetry. A mixed model generalizes it; it does not compete with it.
Nothing you know about ANOVA is wasted. It is a special case.
Why mixed models
Side by side
| t-test / LM on means | RM-ANOVA on means | Mixed model | |
|---|---|---|---|
| Uses trial-level data | No, averages first | No, averages first | Yes |
| Accounts for repeated measures | Only if paired | Yes | Yes |
| Missing cell or dropped trials | Paired: drops the participant | Drops the participant | Keeps what they did |
| Unequal trial counts | Every mean weighted equally | Every mean weighted equally | Weighted by the data behind it |
| Continuous predictors (speed, magnitude, time) | Person-level only | Awkward: ANCOVA or binning | Yes, including trial-level |
| Sphericity assumption | n/a | Yes, needs corrections | Covariance modelled |
| Crossed factors (participants × muscles) | No | No | Yes |
| Separates within- from between-person variance | No | Partly | Yes, reported |
The row that matters most in practice is missing data. One bad session costs RM-ANOVA a whole participant.
Why mixed models
Why it is becoming the standard
- Neuroscience journals were told directly. Ignoring nesting inflates false positives: Aarts et al. 2014, Nature Neuroscience; Yu et al. 2022, Neuron.
- Psychology's replication push made it the default for repeated-trial designs, and made "treat stimuli as random too" mainstream (Judd, Westfall & Kenny 2012; Barr et al. 2013).
- The software matured.
lme4,lmerTestandemmeansmake it routine in R, and reviewers now ask for it. - Lab data are messy. Dropped trials, a missed session and marker dropout are handled without deleting people.
The Yu et al. Neuron paper is the one to send a skeptical co-author.
Random effects
Fixed or random?
Random
Something you sampled and want to generalize beyond: participants, stimuli, sometimes sessions. The model estimates each one's deviation and how much they vary (an SD).
Fixed
Something you manipulated, or whose specific levels you care about: perturbation direction, speed, group. The model estimates each effect directly.
Rule of thumb: with fewer than about 5 levels, a random variance is hard to estimate, so treat the factor as fixed.
Question to ask about any factor: if I reran the study, would I get the same levels? Same directions, yes, so fixed. Same people, no, so random.
Random effects · interactive
Try it: Michael Freeman's walkthrough
Use the tabs across its top, or scroll inside the window: Nested Data, Linear Model, Random Intercept, Random Slope, then Random Slope + Intercept. Read its groups as participants.
This viewer can't show other websites inside the page. Open the walkthrough in its own tab instead.
Open mfviz.com/hierarchical-models ↗- Random intercept: everyone has their own baseline, and everyone responds the same amount.
- Random slope: everyone responds by a different amount. Rarely fitted alone.
- Both: their own baseline and their own sensitivity, plus a correlation between the two. Example: people with high baseline activity may scale up less.
Random effects
Partial pooling is the idea that makes it click
Each person's line is a compromise between their own data and the group line.
| Approach | Each person's estimate is | Problem |
|---|---|---|
| Complete pooling (one LM) | The group line | Pretends people are identical |
| No pooling (a fit per person) | Their data only | Noisy; overfits people with few trials |
| Partial pooling (mixed model) | A weighted blend of the two | Needs enough people to estimate the variance |
Someone with 5 noisy trials is pulled strongly toward the group. Someone with 60 clean trials mostly keeps their own line. That pull is shrinkage, and it prevents extreme estimates that only rest on a few trials.
Shrinkage sounds like bias. Think of it as borrowing strength: the group tells you what is plausible for one noisy person.
Random effects
Random slopes protect your inference
If people truly differ in their response to a condition and you fit only a random intercept, the model counts that disagreement as noise and overstates your confidence in the condition effect.
"Keep it maximal"
Barr et al. 2013: include a random slope for every within-subject factor the design supports.
"But be parsimonious"
Matuschek et al. 2017: maximal models often fail to converge or overfit. Simplify based on evidence, not habit.
| lme4 formula | Meaning |
|---|---|
(1 | subject) | Random intercept per participant |
(1 + cond | subject) | Intercept and condition slope, correlated |
(1 + cond || subject) | Same, correlation fixed at 0 (behaves as expected for numeric predictors) |
(1 | subject/session) | Sessions nested in participants |
(1 | subject) + (1 | muscle) | Crossed: every participant has every muscle |
This is where most arguments with reviewers happen. Pick a strategy before you look at p-values, and write it down.
Trial-level data
Every trial goes in, not per-person averages
What you gain
- Trial-to-trial variability stays, so the model can tell a consistent person from a noisy one.
- Unequal trial counts are fine: 12 usable trials and 40 both count, weighted by the evidence.
- Trial-level covariates: trial number, pre-perturbation posture, step width.
What to watch
- 2,000 rows from 12 people is still 12 people for claims about people.
- If people differ in how they respond, a missing random slope does more damage here: many trials make a within-subject effect look far too precise.
- Trials drift over a session (adaptation, fatigue). Try trial number as a covariate.
- Single outlier trials now carry weight. Set exclusion rules before you look.
- Trials lost because someone stepped or fell are informative, not random.
More trials sharpen each person's estimate. More people sharpen the claim about people. Those are different knobs.
Degrees of freedom
df are estimated, not counted
In ANOVA, df come straight from the design. A mixed model has no exact count, so Satterthwaite or Kenward-Roger estimates df from the design and the variance components. Expect fractional df (22.7) that differ from coefficient to coefficient.
| Effect | df should look like |
|---|---|
| Between-subject (group) | About participants minus groups, however many trials there are |
| Within-subject, with a random slope | Close to the number of participants |
| Within-subject, no random slope | Can climb toward the trial count. Worth checking. |
Huge df are a prompt to check, not proof of a mistake. If people really do respond alike, leaving out the random slope gives nearly the same estimate and SE, and only the df balloon. If people differ, the SE is too small as well, and the inflated df add to the overconfidence.
m_int <- lmer(y ~ cond + (1 | subject), data = d) m_slope <- lmer(y ~ cond + (1 + cond | subject), data = d) anova(m_int, m_slope) # does the random slope improve fit? VarCorr(m_slope) # how big is the slope SD? summary(m_int)$coefficients; summary(m_slope)$coefficients # compare SEs and df
The quickest check on this page: open your last lmerTest output and look at the df. If they are huge, fit it with the random slope and see whether anything changes.
Design choice
Keep both time points; lean away from difference scores
# difference score: the baseline is gone lmer(delta ~ cond + (1 | subject), data = d_diff) # both points plus a phase factor: phase x cond answers the "difference" question m <- lmer(y ~ phase * cond + (1 + phase | subject), data = d_long) # phase = baseline / post emmeans(m, pairwise ~ phase | cond) # change within each condition
Why keep both
- Baseline is information: were groups already different? Does change depend on starting level (regression to the mean)?
- var(Δ) = var(pre) + var(post) − 2·cov. With a weak pre/post correlation, Δ is noisier than either measurement.
- Someone missing one time point still contributes.
- Plots show real levels, not just a change.
When Δ is defensible
Baseline is very consistent across people and conditions, strongly correlated with post, and the question is only about change. You get a simpler model that converges more easily.
Check first: plot the baselines, fit both versions, and confirm they agree. When in doubt, keep both points.
A third option, common in clinical trials: baseline as a covariate, post ~ baseline + cond.
Pitfalls · 1
summary() answers questions about your reference level
R uses treatment (dummy) coding by default. Each coefficient is a difference from the baseline level, holding every other factor at its baseline.
- With
cond * group, thecondrow is the condition effect in the reference group only. It is not a main effect. - The intercept is the prediction when every numeric predictor is 0. Speed = 0 m/s is meaningless, so centre numeric predictors.
- Relevel a factor and every coefficient, SE and p-value moves, while the fit stays identical.
options(contrasts = c("contr.treatment", "contr.poly"))
m_a <- lmer(onset_ms ~ cond * group + (1 | subject), data = d)
d$group <- relevel(d$group, ref = "B")
m_b <- update(m_a, data = d)
cbind(fixef(m_a), fixef(m_b)) # different numbers...
c(logLik(m_a), logLik(m_b)) # ...identical fit
Try it yourself. The p-values change while the log-likelihood stays identical.
Pitfalls · 2
Ask your real questions with emmeans
Estimated marginal means per condition, averaged fairly over the other factors, and the contrasts you actually care about.
library(lme4); library(lmerTest); library(emmeans)
options(contrasts = c("contr.sum", "contr.poly")) # sum-to-zero before Type III tests
d$speed_c <- d$speed - mean(d$speed) # centre: intercept = average speed
m <- lmer(onset_ms ~ cond * group + speed_c + (1 + cond | subject), data = d)
anova(m) # Type III F tests, Satterthwaite df
emm <- emmeans(m, ~ cond | group) # condition means within each group
pairs(emm, adjust = "holm") # corrected pairwise contrasts
emtrends(m, ~ group, var = "speed_c") # speed slope per group
For lmer, emmeans uses Kenward-Roger df by default and switches to asymptotic above 3,000 observations. Trial-level data hit that often; report which one you used.
Rule: summary() is for checking the model, emmeans is for answering the question.
Pitfalls · 3
p-values and confidence intervals take more thought
p-values
lme4 prints none on purpose: residual df are not well defined. lmerTest adds Satterthwaite; pbkrtest gives Kenward-Roger. Both are fine at reasonable n. Below about 10 participants, prefer a likelihood-ratio test or bootstrap.
How they differ: Satterthwaite only estimates the df, using the model's standard errors as they are. Kenward-Roger first adjusts the standard errors (usually upward) for the fact that the variance components were themselves estimated, then estimates df. So it is more conservative in small samples, needs a REML fit, and gets slow on large data (emmeans stops using it above 3,000 observations).
Confidence intervals
confint(m)defaults to profile likelihood: slower, correct, and fails loudly on a barely identified model.method = "Wald"is fast, fine for fixed effects in large samples, and wrong for variance components.predict()gives no SEs for lmer. Use emmeans, ggeffects or a bootstrap for bands.
confint(m, method = "profile") confint(m, method = "boot", nsim = 1000, parm = "beta_") # parametric bootstrap, fixed effects
Always say which df method you used in the methods section. Reviewers increasingly ask.
Pitfalls · 4
Bootstrapping
Parametric
bootMer() simulates new data from the fitted model and refits. It gives CIs on anything, including variance components and derived quantities, but it assumes the model is right.
Case (nonparametric)
Resample participants, not trials. Resampling trials repeats the pseudoreplication mistake. See lmeresampler.
set.seed(1) b <- bootMer(m, FUN = fixef, nsim = 1000, parallel = "multicore", ncpus = 4)
1,000 refits of a random-slope model takes minutes to hours. Parallelize and set a seed.
The resample-participants point is the one people get wrong.
Pitfalls · 5
Power analysis means simulation
There is no G*Power button. Power depends on the number of participants, trials per participant, and every variance component.
- Take variance components (intercept SD, slope SD, residual SD) from pilot data or a published study.
- Set the effect to the smallest one you would care about, not the pilot estimate. Power from a pilot's own effect is circular.
- Simulate many datasets, fit each, and count the significant results.
- Explore the trade-off. When slopes vary a lot across people, participants buy more power than trials.
library(simr)
m0 <- lmer(onset_ms ~ speed_c + (1 + speed_c | subject), data = pilot)
fixef(m0)["speed_c"] <- 0.5 # smallest effect of interest
m_big <- extend(m0, along = "subject", n = 30) # pretend 30 participants
powerSim(m_big, test = fixed("speed_c", "t"), nsim = 200)
powerCurve(m_big, test = fixed("speed_c", "t"), along = "subject", nsim = 200)
Code to steal: gitlab.com/neurotrophy-git/mem-powersimulation, the simulation-based power analysis from one of the lab's own projects. Start from it rather than from scratch.
The linked repo is a working template. Adapt the simulation to your design, not just the numbers.
Pitfalls · 6
Plots can mislead ANOVA-trained eyes
- The error bars overlap, yet every participant goes up. The mixed model sees that consistency; the bar chart hides it.
- With unbalanced data, raw means will not match model estimates. Label which one you plot.
- Better: per-participant lines with the emmeans estimate and CI on top. If you must use error bars, use within-subject intervals (Cousineau–Morey).
subj <- aggregate(onset_ms ~ subject + cond, data = d, FUN = mean)
em <- as.data.frame(emmeans(m, ~ cond)) # emmean, lower.CL, upper.CL (asymp.LCL/UCL above 3,000 obs)
ggplot(subj, aes(cond, onset_ms, group = subject)) +
geom_line(alpha = 0.3) +
geom_pointrange(data = em, inherit.aes = FALSE,
aes(cond, emmean, ymin = lower.CL, ymax = upper.CL), size = 0.8)
In a within-subject design, overlapping error bars do not mean there is no effect. This figure shows why.
Pitfalls · 7
A sentence each
- Singular fits and convergence warnings: a variance at 0 or a correlation at ±1 means the data cannot support that structure. Check
isSingular(), rescale, tryallFit(), then simplify on evidence. - REML vs ML: compare models that differ in fixed effects with ML.
anova(m1, m2)refits automatically. - Effect size: marginal R² (fixed only) vs conditional R² (fixed + random), Nakagawa & Schielzeth 2013, via
performance::r2(). - Within vs between: split a time-varying covariate (fatigue, step width) into a person mean plus a deviation, or the model blends two questions.
- Non-normal outcomes (fall or no fall, counts, RTs) need
glmerorglmmTMB. Check residuals withDHARMa. - Report the full formula, contrast coding, df method, convergence handling, and package versions.
isSingular(m); summary(allFit(m)) performance::r2(m); performance::check_model(m)
Sources
Read more
- Aarts et al. (2014). A solution to dependency: using multilevel analysis to accommodate nested data. Nat Neurosci 17:491–496. PubMed
- Yu et al. (2022). Beyond t test and ANOVA: applications of mixed-effects models for more rigorous statistical analysis in neuroscience research. Neuron 110:21–35. PubMed
- Barr, Levy, Scheepers & Tily (2013). Random effects structure for confirmatory hypothesis testing: Keep it maximal. J Mem Lang 68:255–278.
- Matuschek et al. (2017). Balancing Type I error and power in linear mixed models. J Mem Lang 94:305–315.
- Judd, Westfall & Kenny (2012). Treating stimuli as a random factor in social psychology. JPSP 103:54–69.
- Bates et al. (2015). Fitting linear mixed-effects models using lme4. J Stat Softw 67(1).
- Kuznetsova et al. (2017). lmerTest package. J Stat Softw 82(13).
- Green & MacLeod (2016). SIMR. Methods Ecol Evol 7:493–498.
- Nakagawa & Schielzeth (2013). R² from GLMMs. Methods Ecol Evol 4:133–142.
- Freeman. An introduction to hierarchical modeling (interactive).
- Lab power-simulation code: mem-powersimulation
Also on my GitLab
Other tools you may find useful
All public, at gitlab.com/neurotrophy-git.