Skip to content

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.

Applied ~11 min10 steps

What runs in CodeSplash

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

Read first

01

How many pigs?

Predict

Predict 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..

02

Measuring the overlap

Read

The 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:

ρ=σbetween2σbetween2+σwithin2\rho = \frac{\sigma^2_{\text{between}}}{\sigma^2_{\text{between}} + \sigma^2_{\text{within}}}

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.

03

The design effect

Read

The 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 mm rows per cluster:

DEFF=1+(m−1)ρ\text{DEFF} = 1 + (m - 1)\rho

Divide your rows by it to get an effective sample size. With 12 weighings per pig and an ICC near 0.780.78:

1+11×0.78≈9.6,859/9.6≈901 + 11 \times 0.78 \approx 9.6, \qquad 859 / 9.6 \approx 90

Those rows carry about the information of 90 independent weighings. Even a small ICC matters when clusters are large: at ρ=0.05\rho = 0.05 with m=41m = 41, DEFF is already 3.

04

Ignore it and see

Explore

BExplorable · 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?

0.50
How sure?
6
20
0.10
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

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.

05

Which predictor pays?

Predict

Predict 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?

Diet pays moreWeek pays moreBoth pay the same
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.

06

Five ways to respect clusters

Read
ApproachWhen it suits youLesson
Analyze one summary per clusterA treatment given to whole clusters, with balanced sizesThis one
Cluster-robust standard errorsOnly the errors need fixing, with many clustersRobust standard errors
Mixed modelYou want group-level variation, or effects within groupsNext three lessons
GEEYou want population-average effectsGEE
Panel fixed effectsUnmeasured unit traits may be tied to the predictorPanel 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.

07

How many clusters is enough?

Reflect

Cluster-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 FF = 104.

A very large FF from a very small R2R^2 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.

08

Check your understanding

Checkpoint

Check 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.

09

Check your own data

In the app

Pick 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.

Python
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}")
R
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)
10

Recap

Recap
  • Rows in a group overlap, so the number of rows overstates your information.
  • The ICC measures that overlap, and 1+(m−1)ρ1 + (m - 1)\rho 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