Date: November 19, 2026
Important
20 minutes · On myCourses
Covers Weeks 11–12: missing data, building models in blocks, and logistic regression. Start when I say go.
When you finish: open today’s activity and do the Set up section so you’re ready for Part A.
When the same person shows up more than once
lm() gets the standard errors wrong when rows aren’t independentThe plan for class
| 💾 Class Check 5 | 20 min |
| Lecture | ~45 min |
| 😴 Activity | ~20 min |
| ☕ Break | |
| 📂 M3 work time | the rest of class |
Note
New packages today: install.packages(c("lme4", "lmerTest")). Load lmerTest after lme4.
400 kids, measured at three waves, one year apart: sleep, stress, depression, anxiety.
So far we’ve used one wave at a time: predict Time 3 from Time 1, one row per kid.
Today’s question uses all three waves at once:
Does depression go up as kids get older? And do girls report more of it?
To answer it, every observation needs its own row.
asap_long <- asap %>%
pivot_longer(starts_with("T"),
names_to = c("wave", ".value"), # "T2_Dep" → wave = 2, column = Dep
names_pattern = "T(\\d)_(.*)") %>%
mutate(wave = as.numeric(wave) - 1) # 0, 1, 2 = years since the first visit
asap_long %>%
filter(ID %in% 1:2) %>%
select(ID, Sex, wave, Age, SleepQual, Dep)# A tibble: 6 × 6
ID Sex wave Age SleepQual Dep
<int> <int> <dbl> <dbl> <dbl> <dbl>
1 1 1 0 7.57 6.57 10.4
2 1 1 1 8.57 6.03 12.1
3 1 1 2 9.57 5.6 13.5
4 2 0 0 8.77 5.61 8.89
5 2 0 1 9.77 5.14 9.35
6 2 0 2 10.8 3.75 14.6
T1_Dep, T2_Dep, T3_Dep. Good for lm() with one time point.Sex and SES repeat on every row. They don’t change.# A tibble: 1 × 3
rows rows_with_dep kids
<int> <int> <int>
1 1200 1076 400
The rows are not independent. A kid who’s high at wave 0 tends to stay high:
set.seed(13)
some_kids <- sample(unique(asap_long$ID), 25)
asap_long %>%
filter(ID %in% some_kids, !is.na(Dep)) %>%
ggplot(aes(wave, Dep, group = ID)) +
geom_line(alpha = 0.4) +
geom_point(alpha = 0.4) +
stat_summary(aes(group = 1), data = asap_long, fun = mean,
geom = "line", color = "#C8102E", linewidth = 1.5) +
scale_x_continuous(breaks = 0:2) +
labs(x = "Wave (years since first visit)", y = "Depression") +
theme_bw(base_size = 15)
Each gray line is one kid. Red is the average.
lm() does with this# A tibble: 3 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 9.40 0.181 51.9 3.61e-295
2 wave 1.53 0.124 12.4 5.59e- 33
3 Sex 0.451 0.199 2.27 2.33e- 2
lm() thinks it has 1076 independent kids. It has 400.
Warning
Asking one person the same question three times is not three people. lm() counts it as three, so it’s too confident: standard errors too small, p-values too small. (Week 10’s assumption #4, independence, the one no plot can fix.)
Give every kid their own intercept, and let the model estimate how much those intercepts vary.
\[ \text{Dep}_{ij} = (b_0 + u_{j}) + b_1\,\text{wave}_{ij} + e_{ij} \]
| Piece | What it is | |
|---|---|---|
| b0, b1 | Fixed effects: one number for everyone | the average kid |
| uj | Kid j’s random intercept: how far they sit above or below average | between kids |
| eij | What’s left at each wave | within a kid |
Two sources of variation instead of one. That’s the whole trick.

lmer(): one new piece of syntax(1 | ID): read it as “an intercept that varies by ID”( is the same formula you’ve written all semesterlmer = linear mixed-effects regression. Mixed = fixed + random.Multilevel, mixed, hierarchical, random-effects: same model, different fields.
The intraclass correlation: the share of variance that sits between kids.
\[ \text{ICC} = \frac{\text{between-kid variance}}{\text{between} + \text{within}} = \frac{2.75}{2.75 + 9.38} = .23 \]
lm() would be fine. Here it isn’t 0.# Fixed Effects
Parameter | Coefficient | SE | 95% CI | t(1071) | p
-------------------------------------------------------------------
(Intercept) | 9.40 | 0.20 | [ 9.01, 9.79] | 47.30 | < .001
wave | 1.53 | 0.10 | [ 1.32, 1.73] | 14.65 | < .001
Sex | 0.46 | 0.25 | [-0.03, 0.94] | 1.85 | 0.065
# Random Effects
Parameter | Coefficient
--------------------------------
SD (Intercept: ID) | 1.82
SD (Residual) | 2.69
lm(): depression rises about 1.53 points per year, holding sex constant.lm() |
lmer() |
|||||
|---|---|---|---|---|---|---|
| b | SE | p | b | SE | p | |
| wave (changes within a kid) | 1.53 | 0.124 | < .001 | 1.53 | 0.104 | < .001 |
| Sex (same on every row) | 0.45 | 0.199 | .023 | 0.46 | 0.247 | .065 |
lm() counted each girl three times. Fixed: SE goes up, and p crosses .05. One model says “girls report more depression”; the honest one says “we can’t tell.”Important
Ignoring the nesting doesn’t just make you overconfident. It makes you wrong in both directions, depending on the level of the predictor.
| Fixed effect | Random effect | |
|---|---|---|
| What it is | One number for everyone | How much people differ |
| ASAP example | Average change per year: 1.53 | SD of kids’ intercepts: 1.82 |
| The question it answers | “What happens on average?” | “How much do kids vary around that?” |
| You report | b, CI, p | SD (or variance), and the ICC |
When is something random? When the levels are a sample from a bigger population you want to generalize to: kids, classrooms, therapists, schools, days. You don’t care about kid #217 in particular.
What’s each kid’s “usual” depression? Three ways to estimate it:
lm() with no ID.) Ignores real differences.lmer() does.pool <- asap_long %>%
filter(!is.na(Dep)) %>%
group_by(ID) %>%
summarise(no_pool = mean(Dep), waves = n()) %>%
left_join(coef(m0)$ID %>% rownames_to_column("ID") %>%
mutate(ID = as.numeric(ID)) %>%
rename(partial = `(Intercept)`), by = "ID")
pool %>%
ggplot(aes(no_pool, partial, color = factor(waves))) +
geom_abline(slope = 1, intercept = 0, linetype = "dashed") +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm", se = FALSE, linewidth = 1.2) +
coord_equal() +
labs(x = "Kid's own mean (no pooling)", y = "lmer estimate (partial pooling)",
color = "Waves observed") +
theme_bw(base_size = 14)
Dashed line = no shrinkage. Every kid gets pulled toward the average (the lines are flatter than the dashed one), and kids seen once get pulled hardest. The model trusts the kids it knows more about.
# A tibble: 3 × 2
waves kids
<int> <int>
1 1 25
2 2 74
3 3 301
lm(T3_Dep ~ T1_Dep ...) dropped every kid missing Time 3. Listwise deletion.lmer() on long data uses every row it has. A kid seen twice still contributes two rows, and still counts.Tip
For longitudinal data, a mixed model is often the simplest honest answer to “what do I do about dropout?”
Random intercepts give every kid their own starting point, but the same slope. Parallel lines.
set.seed(19)
sim <- expand_grid(person = 1:15, time = 0:9) %>%
group_by(person) %>%
mutate(u0 = rnorm(1, 0, 25), u1 = rnorm(1, 0, 6)) %>%
ungroup() %>%
mutate(`Random intercepts only` = 250 + u0 + 10 * time,
`Random intercepts + slopes` = 250 + u0 + (10 + u1) * time) %>%
pivot_longer(starts_with("Random"), names_to = "model", values_to = "y") %>%
mutate(model = fct_rev(model))
ggplot(sim, aes(time, y, group = person)) +
geom_line(alpha = 0.6) +
facet_wrap(~ model) +
labs(x = "Time", y = "Outcome") +
theme_bw(base_size = 15)
Random slopes let each person have their own rate of change, and estimate how much those rates vary.

(wave | ID): “the intercept and the effect of wave both vary by ID.” (The 1 is implied.)
Only within-person predictors can have random slopes. (Sex | ID) makes no sense: Sex doesn’t change within a kid, so there’s no kid-specific slope to estimate.
boundary (singular) fit: see help('isSingular')
“Singular fit” plus a correlation of 1.00 between intercepts and slopes: the model is asking for more than the data can tell it.
Tip
A warning from lmer() is information, not noise. You’ll fit random slopes that work in the activity, with 10 observations per person.
| Predictor | Changes within a kid? | Can tell you about… |
|---|---|---|
| Sex, SES | No | Differences between kids |
| wave | Yes, by design | Change within a kid |
| SleepQual | Yes, and kids differ on average | Both, mixed together |
A time-varying predictor like SleepQual carries two questions:
These can have different answers.
# Fixed Effects
Parameter | Coefficient | SE | 95% CI | t(1070) | p
-------------------------------------------------------------------
(Intercept) | 8.46 | 0.43 | [ 7.62, 9.30] | 19.80 | < .001
wave | 1.53 | 0.10 | [ 1.33, 1.74] | 14.69 | < .001
Sex | 0.46 | 0.24 | [-0.02, 0.94] | 1.88 | 0.060
SleepQual | 0.18 | 0.07 | [ 0.04, 0.33] | 2.48 | 0.013
# Random Effects
Parameter | Coefficient
--------------------------------
SD (Intercept: ID) | 1.78
SD (Residual) | 2.70
One slope, 0.18. Between, within, or some average of the two? You can’t tell.
asap_long <- asap_long %>%
group_by(ID) %>%
mutate(sq_kid_mean = mean(SleepQual, na.rm = TRUE), # the kid's usual level
sq_within = SleepQual - sq_kid_mean) %>% # this wave vs. their usual
ungroup() %>%
mutate(sq_between = sq_kid_mean - mean(sq_kid_mean, na.rm = TRUE)) # kid's usual vs. other kids
m_split <- lmer(Dep ~ wave + Sex + sq_between + sq_within + (1 | ID), data = asap_long)
model_parameters(m_split)# Fixed Effects
Parameter | Coefficient | SE | 95% CI | t(1069) | p
-------------------------------------------------------------------
(Intercept) | 9.39 | 0.20 | [ 9.01, 9.78] | 47.82 | < .001
wave | 1.52 | 0.10 | [ 1.32, 1.73] | 14.62 | < .001
Sex | 0.46 | 0.24 | [-0.01, 0.94] | 1.90 | 0.057
sq between | 0.38 | 0.10 | [ 0.17, 0.58] | 3.63 | < .001
sq within | -0.01 | 0.10 | [-0.22, 0.19] | -0.12 | 0.908
# Random Effects
Parameter | Coefficient
--------------------------------
SD (Intercept: ID) | 1.77
SD (Residual) | 2.69
Person-mean centering: SleepQual − kid's mean → the within effect
Grand-mean centering: kid's mean − mean of all kids → the between effect, with an intercept for the average kid
Grand-mean centering raw SleepQual doesn’t separate the two; it only shifts the intercept (Week 9 callback)
Important
Between-person effects describe how people differ. Within-person effects describe how a person changes. Most psychological theories are about the second; most cross-sectional data can only show the first.
Because each child contributed up to three observations, we fit a linear mixed model with random intercepts for child using the
lme4(Bates, et. al, 2015). The model used 1076 observations from 400 children across 3 waves of data. In a null model, 23% of the variance in depression was between children (ICC = .23). Depression increased by 1.53 points per year, 95% CI [1.32, 1.73], p < .001. Girls and boys did not differ reliably, b = 0.46, 95% CI [-0.03, 0.94], p = .065. Fixed effects explained 13% of the variance (marginal R²); including child-level differences, 40% (conditional R²). A model adding random slopes for wave was singular, so we retained random intercepts only.
Note
You should always cite the libraries that you use in R. This gives the developers credit. You can find the citation of any package using citation()
lm() is overconfident about anything that’s constant within a person. Check: does n_distinct(ID) equal nrow()?lm() vs. lmer(), side by sidelm() |
lmer() |
|
|---|---|---|
| Data | One row per person | One row per observation (long) |
| Assumes | Every row independent | Rows within a cluster are related |
| R | lm(y ~ x) |
lmer(y ~ x + (1 | id)) |
| Coefficients | b | Fixed effects: read the same as b |
| Extra output | — | Random effects: SDs, the ICC |
| Compare models | anova() → F |
anova() → χ² (likelihood ratio) |
| Fit | R² | Marginal and conditional R² |
| Missing waves | Drops the person | Uses the rows they have |
It’s not just time. Any time observations come in groups:
| Level 2 (cluster) | Level 1 (observation) |
|---|---|
| Person | Days in a diary study, trials in an experiment |
| Classroom | Students |
| Therapist | Clients |
| Couple, family | Partners, siblings |
| Stimulus | Ratings of it |
For your final project: if any person (or classroom, or therapist) shows up in more than one row of your analytic data, use the multilevel line under Model 1 in memo.qmd, and come talk to me.
Tip
~20 min · Pairs · Data built into lme4, nothing to download
18 people, 3 hours in bed per night, reaction time measured every day for 10 days.
Random intercepts, random slopes, and whose reaction time falls apart fastest.
Due Monday 11/30. Use the rest of class. I’ll come around.
M3 checklist
Binary outcome? glm(..., family = binomial). Many rows per person? Today’s model. Flag me down either way.
🦃 No class Thursday 11/26: Thanksgiving
📂 M3 — Describe and build an initial model, due Monday 11/30
📖 Reading for Making R Work for You:
Bring in any R related stuff that you’ve found along the way! Or questions about anything so far.
🔁 M4 — Reproducibility swap, in class Thursday 12/3. Bring a project that renders from a fresh R session.