The idea
Resampling the data with replacement and recomputing a statistic many times is the bootstrap, a way to estimate uncertainty without a formula. It only works if the resampled units are independent. When rows come in groups, such as many questions about one document or many sessions from one user, rows inside a group move together, and resampling rows makes the interval too narrow.
cluster_interval resamples groups instead. It reduces each group to the mean of its paired differences, so every group counts equally whatever its size, then draws that many group means with replacement, repetitions times, using random.Random(seed). The 2.5th and 97.5th percentiles of the resampled averages, found by linear interpolation, are the bounds.
How it works
- Validate aligned nonempty inputs, string group names, finite deltas and an integer
repetitions of at least 2. - Collect the deltas of each group in
buckets and compute one mean per group, in sorted group order. - Raise
ValueError if fewer than two groups remain, since one unit says nothing about spread. - For each repetition, draw as many group means as there are groups, with replacement, and record their average.
- Sort the recorded averages and interpolate at positions
(R - 1) * 0.025 and (R - 1) * 0.975. - Return
estimate, the mean of the group means, with low, high and the group count.
What it costs
- Time
- O(n + R·g + R log R)
- Space
- O(n + R)
Grouping reads the n rows once, each of the R repetitions draws g group means, and the R averages are sorted for the percentiles.
Where it is used
- Stata's
bootstrap command has a cluster() option that resamples whole clusters, such as patients or firms, instead of rows. - Bakshy and Eckles's 2013 paper on Facebook experiments evaluates bootstraps that resample users and items, because observations sharing a user are dependent.
- Anthropic's paper Adding Error Bars to Evals recommends clustered standard errors when several evaluation questions share one passage.
Watch out for
- Resampling rows instead of groups, which treats correlated rows as independent and produces an interval that is too narrow.
- Pooling all rows into one mean, so a group with many rows dominates; the Lab averages group means with equal weight.
- Iterating over groups in dict or input order: sorting the group names is what makes a seeded result independent of row order.