Clustered data: when your rows aren't independent
Pupils share classrooms, and repeated measures share a person. Rows in the same group overlap in what they tell you. Learn to measure that overlap, and see what happens to a test that ignores it.
What runs in CodeSplash
- Linear mixed model (random intercepts and slopes) Verified in Python and R
- Linear regression (OLS) Verified in Python and R
You will be able to
- Say how many independent units your data really contain
- Read an intraclass correlation and compute a design effect
- Explain why clustering hurts between-group predictors more than within-group ones
- Choose among cluster means, robust errors, mixed models, GEE and panel models
How many pigs?
PredictPredict first
A feeding trial weighs pigs every week for 12 weeks, and each pig stays on one diet. The file has 859 rows. For comparing diets, how many independent units do you think it holds?
Make your guess between 0 and 900 independent units, then reveal.
Reveal
72: that's the number of pigs. Weighing a heavy pig again tells you little you didn't already know, and diets were given to pigs, not to weighings. Rows that share a group are clusteredCluster variableThe column that says which rows belong together (same patient, school, store), so their dependence is accounted for..
Measuring the overlap
ReadThe intraclass correlationIntraclass correlationThe share of variance due to differences between groups (or raters' agreement on the same subjects). is the share of variance that lies between groups:
At 0, group membership tells you nothing, and rows behave independently. At 1, every row in a group is identical, so one row per group would do.
After week and diet, the pigs' ICC is 0.777: two weighings of the same pig are far more alike than two weighings of different pigs.
The design effect
ReadThe design effectDesign effectHow much the sampling design inflates a variance compared with a simple random sample of the same size. says how much clustering inflates the variance of a mean, with rows per cluster:
Divide your rows by it to get an effective sample size. With 12 weighings per pig and an ICC near :
Those rows carry about the information of 90 independent weighings. Even a small ICC matters when clusters are large: at with , DEFF is already 3.
Ignore it and see
ExploreBExplorable · When observations come in clusters
What happens to a t test when students come in classrooms and you ignore it?
There is no true effect. How often does the naive t test reject?
Commit your prediction above to see the result
Make your prediction to see the result.
There's no true effect here. Set the Intraclass correlation to 0, and the t test rejects about 5% of the time, as promised. Now raise it a little, and then raise Observations per cluster.
The false-positive rate climbs, and adding rows to each cluster makes it worse, not better. Testing cluster means stays honest throughout.
Which predictor pays?
PredictPredict first
Diet is fixed for each pig. Week changes within each pig. A naive model treats every row as independent. Which predictor's standard error does it understate most?
Reveal
Diet. It only varies between pigs, so its effective sample is close to the number of pigs. Week varies within each pig, so every pig acts as its own control. Clustering can even make within-group comparisons more precise.
Five ways to respect clusters
Read| Approach | When it suits you | Lesson |
|---|---|---|
| Analyze one summary per cluster | A treatment given to whole clusters, with balanced sizes | This one |
| Cluster-robust standard errors | Only the errors need fixing, with many clusters | Robust standard errors |
| Mixed model | You want group-level variation, or effects within groups | Next three lessons |
| GEE | You want population-average effects | GEE |
| Panel fixed effects | Unmeasured unit traits may be tied to the predictor | Panel models |
The summary approach is easy to overlook. With equal cluster sizes, a t test on cluster means gives valid inference for a cluster-level treatment.
How many clusters is enough?
ReflectCluster-robust errors learn the correlation from the clusters themselves, so they need many of them. This survey model clusters on 4 groups. It explains 2.0% of the variance, yet reports = 104.
A very large from a very small is the warning sign: the standard errors are far too small. What would you do with data from only a few sites? Think about it before the next lesson, where mixed models have the same problem with variances.
Check your understanding
CheckpointCheck yourself
Each cluster has 11 rows, and the ICC is 0.2. What's the design effect?
Show the answer
Answer: 3
1 + (11 − 1) × 0.2 = 3. The variance of a mean is three times what independent rows would give.
Check yourself
You have 1,200 rows and a design effect of 3. What's the effective sample size?
Show the answer
Answer: 400
1,200 / 3 = 400. Rows overlap, so they carry the information of about 400 independent ones.
Check yourself
Four cages per treatment, ten mice per cage, and the treatment goes in the cage's water. What's the unit for testing the treatment?
Show the answer
Answer: b
The treatment was assigned to cages. Treating mice as independent here is called pseudoreplication, and it makes the test far too eager.
Check yourself
Your outcome has an ICC of 0.01 and clusters of 500 rows. Can you ignore clustering?
Show the answer
Answer: b
1 + 499 × 0.01 ≈ 6. Large clusters turn a tiny ICC into a big design effect.
Check your own data
In the appPick your Outcome and Fixed effects, and put the unit that rows belong to in Grouping factor. Read the ICC on the card, then ask whether anything you ran earlier treated those rows as independent.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("s1_dietox.csv").rename(columns={"vitamin E": "vitamin"}).dropna()
df["pig"] = df["pig"].astype(str)
fit = smf.mixedlm("weight ~ week + copper + vitamin", df, groups="pig").fit()
between = fit.cov_re.iloc[0, 0]
icc = between / (between + fit.scale)
m = df.groupby("pig").size().mean()
deff = 1 + (m - 1) * icc
print(f"ICC = {icc:.3f}, design effect = {deff:.1f}, effective n = {len(df) / deff:.0f}")library(lme4)
df <- read.csv("s1_dietox.csv", check.names = FALSE)
names(df)[names(df) == "vitamin E"] <- "vitamin"
df <- na.omit(df)
fit <- lmer(weight ~ week + copper + vitamin + (1 | pig), data = df)
vc <- as.data.frame(VarCorr(fit))$vcov
icc <- vc[1] / sum(vc)
m <- mean(table(df$pig))
deff <- 1 + (m - 1) * icc
c(icc = icc, design_effect = deff, effective_n = nrow(df) / deff)Recap
Recap- Rows in a group overlap, so the number of rows overstates your information.
- The ICC measures that overlap, and converts it into a design effect.
- Predictors that vary only between clusters pay most.
- Adding rows per cluster has limits. Adding clusters is what buys precision.
Concepts in this lesson