Exercise: hierarchical models
Goal
By the end of this exercise you should be able to:
- tell a biological replicate from a technical one, and count the effective sample size of a design,
- recognise pseudoreplication in a described analysis, say what goes wrong, and see it in a simulation,
- compute a partial-pooling (shrinkage) estimate by hand from the precision-weighted-average formula,
- read the two variance components (\(\sigma^2\) within, \(\tau^2\) between) and turn them into an ICC,
- write the R model formula
y ~ x + (1 | group)and say what each part means in bothlme4andbrms.
Background
Grouped data have (at least) two levels of variation. Each measurement is the overall mean (a fixed effect), plus a patient level (how far this patient sits from the overall mean, a random effect), plus a measurement level (noise within the patient):
- \(\sigma^2\) — within-group (technical / measurement) variance: how much repeated measurements of one patient scatter.
- \(\tau^2\) — between-group (biological) variance: how much the patients’ own means scatter around the overall mean.
For measurement \(j\) in group \(i\):
\[ y_{ij} = \mu + b_i + \varepsilon_{ij}, \qquad b_i \sim \mathcal N(0,\tau^2), \quad \varepsilon_{ij} \sim \mathcal N(0,\sigma^2). \]
\(\mu\) is the overall mean (fixed effect), \(b_i\) group \(i\)’s deviation (random effect, a draw from a shared \(\mathcal N(0,\tau^2)\)), and \(\varepsilon_{ij}\) the measurement noise.
Partial pooling. The estimate for a group is a weighted average of its own mean \(\bar y\) (from \(n\) measurements) and the grand mean \(\hat\mu\). The weight \(w\) says how much the group’s own data are worth compared with the crowd: \(n/\sigma^2\) is the worth of its own data, \(1/\tau^2\) the worth of the crowd, and \(w\) is the group’s share.
\[ \text{estimate} = w\,\bar y + (1-w)\,\hat\mu, \qquad w = \frac{n/\sigma^2}{\,n/\sigma^2 + 1/\tau^2\,}. \]
The pull of the estimate toward \(\hat\mu\) is shrinkage; it is larger when \(n\) is small or \(\tau^2\) is small.
Variance partition. The intraclass correlation
\[ \text{ICC} = \frac{\tau^2}{\tau^2 + \sigma^2} \]
is the fraction of variance that is between groups — how much your hierarchy matters.
By hand
B1. A study reports: “We measured a protein in 4 mice, taking 50 sections per mouse (n = 200), and found a significant difference between genotypes (p < 0.001).” For the between-genotype question, what is the relevant number of independent units? Name the error being made.
B2. For each design, say whether the extra measurements are biological or technical replicates: (a) the same blood sample split into three tubes and each assayed once; (b) three separately recruited patients, each assayed once; (c) one cell line grown, then split and sequenced in three lanes; (d) three independently grown cultures of the same cell line, each sequenced once.
B3. A group has \(n = 4\) measurements with sample mean \(\bar y = 10\). The grand mean is \(\hat\mu = 6\), the within-group variance is \(\sigma^2 = 8\), and the between-group variance is \(\tau^2 = 2\). (a) Compute the weight \(w\). (b) Compute the partial-pooling estimate. (c) In one sentence, why is the estimate between 6 and 10?
B4. Using the same \(\sigma^2 = 8\), \(\tau^2 = 2\), \(\hat\mu = 6\), now consider a group with only \(n = 1\) measurement whose single value is \(\bar y = 10\). Compute \(w\) and the estimate. Compared with B3, does this group shrink more or less toward the grand mean? Explain in terms of \(n\).
B5. With \(\sigma^2 = 8\) and \(\tau^2 = 2\), compute the ICC. Interpret it: if two measurements come from the same group, how correlated are they, and does grouping matter much here?
B6. (optional) Take the partial-pooling weight \(w = \dfrac{n/\sigma^2}{n/\sigma^2 + 1/\tau^2}\). Show algebraically that: (a) as \(\tau^2 \to 0\), \(w \to 0\) (which pooling regime is this?); (b) as \(\tau^2 \to \infty\), \(w \to 1\) (which pooling regime is this?).
B7. (design) You have budget for 40 assays and want to compare treated vs control. You can spend it as 4 patients × 10 measurements or 20 patients × 2 measurements. If the ICC is high (patients differ a lot, within-patient noise is small), which design gives you more power for the between-patient comparison, and why?
Explore
The demo below simulates eight patients with \(n\) from 1 to 20 measurements, using the numbers of B3–B5: \(\sigma^2 = 8\), true \(\tau^2 = 2\), overall mean 6. Open dots are raw patient means \(\bar y\), filled dots the partial-pooling estimates, the dashed line the grand mean \(\hat\mu\), and the green tick the true patient mean (known only because the data are simulated). The weight \(w\) is printed on the right. Do B3–B4 by hand first.
E1. Click true τ² (\(\tau^2 = 2\)). Read the weight of the \(n = 1\) patient. Does it match your B4 answer? Which patients would have the weight \(0.5\) of B3?
E2. Drag \(\tau^2\) to 0 and then to \(\infty\). Describe where the filled dots go in each case and match each end to a pooling regime (optional B6 shows the same with algebra).
E3. Look at the total error² vs truth box and the red curve. Which of no pooling, complete pooling and partial pooling at the true \(\tau^2\) has the smallest total error? Press new data five times: is the winner always the same?
E4. With \(\tau^2 = 2\), find a patient whose filled dot is further from its green tick than its open dot is. How can shrinkage make a single patient worse and still be a good idea?
The second demo simulates 1000 studies of control vs treated patients, several cells per patient, and analyses each study twice: once treating every cell as an independent sample, once averaging per patient first (about what the mixed model does). It starts at the setting of B7: a budget of 20 cells per group, ICC 0.8, and a real treatment difference of 1. Do B7 first.
E5. Tick fixed budget. (a) Click 2 × 10 (2 patients × 10 cells per group, i.e. 4 patients × 10 measurements in total) and then 10 × 2 (20 patients × 2). In how many of the studies does the per-patient analysis find the real difference? Does this match your B7 answer? (b) The “every cell as a sample” bar looks better at 2 × 10. Set true difference to 0 and look at that bar again. Why should you not trust its high success rate?
E1. \(w = 0.20\) for the \(n = 1\) patient, as in B4. A weight of \(0.5\) needs \(n/\sigma^2 = 1/\tau^2\), i.e. \(n = 4\); no patient here has exactly 4 measurements, so the \(n = 3\) and \(n = 5\) patients bracket it (\(w = 0.43\) and \(0.56\)).
E2. At \(\tau^2 = 0\) all weights are 0 and every filled dot sits on the grand mean: complete pooling. At \(\tau^2 = \infty\) all weights are 1 and every filled dot sits on its open dot: no pooling. In between, small-\(n\) patients move most.
E3. On the first data set partial pooling has the smallest total error (about 13 vs 17 for complete and 23 for no pooling). Over repeated data sets partial pooling usually wins, but not every time: on some data sets complete pooling or no pooling happens to do better. Shrinkage lowers the error on average.
E4. A patient whose true mean really is far from the grand mean gets pulled toward the centre, away from its truth. Shrinkage trades a little bias for individual extreme groups against a large reduction in noise for small groups; summed over all patients, the error is usually smaller.
E5. (a) The per-patient analysis finds the difference in about 11% of studies with 2 × 10, and about 62% with 10 × 2: same number of cells, far more power with more patients, as in B7. With ICC 0.8 the 10 cells of one patient are nearly copies of each other. (b) With no true difference the “every cell as a sample” analysis still calls about 59% of the studies significant, where a fair test gives 5%: it counts the cells as independent (pseudoreplication), so its “power” is bought with false alarms. Only the per-patient analysis stays near 5%.
In R
R is only for confirming the by-hand answers and seeing the model syntax. Nothing here is executed at build time (no packages are installed), so treat these as templates to run in your own session.
Confirm a shrinkage calculation (base R, no packages)
# B3 by hand, reproduced in R
n <- 4
ybar <- 10
mu_hat <- 6
sigma2 <- 8
tau2 <- 2
w <- (n / sigma2) / (n / sigma2 + 1 / tau2)
est <- w * ybar + (1 - w) * mu_hat
c(weight = w, estimate = est) # compare against your hand answerThe ICC
sigma2 <- 8
tau2 <- 2
icc <- tau2 / (tau2 + sigma2)
icc # fraction of variance that is between-groupFitting the model (templates — run in your own session)
# Frequentist multilevel model
library(lme4)
set.seed(1)
d <- data.frame(patient = factor(rep(seq_len(40), each = 4)),
treatment = rep(c("control", "control", "treated", "treated"), 40))
patient_effect <- rnorm(40, sd = sqrt(2))
d$biomarker <- 6 + 1.5 * (d$treatment == "treated") +
patient_effect[as.integer(d$patient)] + rnorm(nrow(d), sd = sqrt(8))
fit <- lmer(biomarker ~ treatment + (1 | patient), data = d)
summary(fit) # fixed effect + variance components (tau^2, sigma^2)
ranef(fit) # the shrunken per-patient offsets# Bayesian version — identical formula
library(brms)
fit <- brm(biomarker ~ treatment + (1 | patient),
data = d, family = gaussian())
summary(fit) # posterior means + credible intervalsTasks
R1. Reproduce B3 and B4 with the base-R shrinkage snippet (change only n). Confirm the \(n = 1\) group shrinks more.
R2. Compute the ICC for \(\sigma^2 = 8, \tau^2 = 2\) (matches B5), then re-compute it for \(\tau^2 = 32\). Which scenario makes grouping matter more?
R3. Write, without running, the lmer/brm formula for a Gaussian biomarker measured once per cell, with cells nested in patients, where you want a treatment fixed effect. How would you extend it if there were repeated measurements of each cell? (Hint below.)
Hints
Ask: does this measurement come from a new, independent biological unit, or from the same unit measured again? A new unit = biological replicate (lets you generalise). Same unit remeasured = technical replicate (only reduces measurement noise). See the replicate discussion in the lecture and the ideas of independent sampling from the Statistics and data science for biologists course.
The number that limits a between-group claim is the number of independent groups, not the total count of measurements. Counting technical/within-unit measurements as if they were independent biological units is pseudoreplication; it makes standard errors too small and p-values too optimistic.
Plug into \(w = \dfrac{n/\sigma^2}{n/\sigma^2 + 1/\tau^2}\), then \(\text{estimate} = w\bar y + (1-w)\hat\mu\). Compute the two “worths” (precisions) first: \(n/\sigma^2\) (how much the group’s own data are worth) and \(1/\tau^2\) (how much the crowd is worth: large when groups cluster tightly). The weight is the group’s worth as a fraction of the total.
\(w\) increases with \(n\): more of its own measurements → the group trusts its own mean more → less shrinkage. With \(n = 1\) the group carries little information, so it leans on the grand mean.
\(\text{ICC} = \dfrac{\tau^2}{\tau^2+\sigma^2}\) is a fraction between 0 and 1. It is both the fraction of total variance that is between-group and the correlation between two measurements from the same group. Near 1 → grouping dominates; near 0 → groups are interchangeable.
Substitute the extreme value of \(\tau^2\) into the weight. For \(\tau^2 \to 0\), the term \(1/\tau^2 \to \infty\) dominates the denominator, so \(w \to 0\). For \(\tau^2 \to \infty\), \(1/\tau^2 \to 0\) vanishes, leaving \(w \to (n/\sigma^2)/(n/\sigma^2) = 1\). Match each to complete vs no pooling.
In lme4::lmer and brms::brm the syntax is identical. (1 | group) = a random intercept per level of group. With one Gaussian response per cell, use (1 | patient) to account for cells sharing a patient; cell-to-cell variability is part of the residual. With repeated observations per cell, nesting can be written (1 | patient/cell) (equivalently (1 | patient) + (1 | patient:cell)). A cell intercept cannot be separated from residual variance with only one response per cell. Crossed factors are separate terms (1 | batch) + (1 | patient). Fixed-effect predictors go on the right-hand side of ~, e.g. biomarker ~ treatment + (1 | patient).
Solutions
B1. The between-genotype comparison has 4 independent units (the 4 mice), not 200. The 50 sections per mouse are technical / within-unit replicates: they make each mouse’s value more precise but do not add independent biological units. Analysing the 200 sections as if independent is pseudoreplication; it understates the standard error and produces a p-value that is too small. The honest design has \(n = 4\) for the genotype question.
B2. (a) Technical — one sample split into three; same biological unit measured three times. (b) Biological — three independently recruited patients; three independent units. (c) Technical — one culture split across lanes; the lanes are sequencing (measurement) replicates of the same unit. (d) Biological — three independently grown cultures; the independent growth is what makes them biological replicates.
B3. (a) Precisions: group precision \(n/\sigma^2 = 4/8 = 0.5\); between-group precision \(1/\tau^2 = 1/2 = 0.5\). \[w = \frac{0.5}{0.5 + 0.5} = \frac{0.5}{1.0} = 0.5.\] (b) \[\text{estimate} = 0.5\cdot 10 + (1-0.5)\cdot 6 = 5 + 3 = 8.\] (c) \(\text{estimate} = 8\) lies between the group’s own mean (10) and the grand mean (6) because the estimate is a compromise: the group’s 4 measurements pull toward 10, the shared distribution of groups pulls toward 6, and here the two carry equal weight.
B4. Now \(n = 1\): group precision \(n/\sigma^2 = 1/8 = 0.125\); between-group precision still \(1/\tau^2 = 0.5\). \[w = \frac{0.125}{0.125 + 0.5} = \frac{0.125}{0.625} = 0.2.\] \[\text{estimate} = 0.2\cdot 10 + 0.8\cdot 6 = 2 + 4.8 = 6.8.\] This group shrinks more toward the grand mean (6.8 is much closer to 6 than B3’s 8 was). Reason: with only \(n = 1\) measurement the group carries little information about itself (\(w = 0.2 < 0.5\)), so the estimate leans heavily on the group of groups.
B5. \[\text{ICC} = \frac{\tau^2}{\tau^2 + \sigma^2} = \frac{2}{2 + 8} = \frac{2}{10} = 0.2.\] Two measurements from the same group are correlated \(0.2\). Only 20% of the total variance is between groups, so grouping matters but is not dominant here — most variation is within groups (measurement/within-unit noise).
B6. (a) As \(\tau^2 \to 0\): \(1/\tau^2 \to \infty\), so the denominator \(n/\sigma^2 + 1/\tau^2 \to \infty\) while the numerator \(n/\sigma^2\) stays finite, giving \(w \to 0\). Then \(\text{estimate} \to \hat\mu\) for every group — complete pooling (groups treated as identical). (b) As \(\tau^2 \to \infty\): \(1/\tau^2 \to 0\), so \(w \to \dfrac{n/\sigma^2}{n/\sigma^2 + 0} = 1\). Then \(\text{estimate} \to \bar y\) — no pooling (each group estimated on its own).
B7. With a high ICC, most of the variance is between patients and within-patient measurements are highly redundant (each extra one adds little new information). The between-patient comparison is limited by the number of patients, so 20 patients × 2 measurements gives far more power than 4 patients × 10 measurements. Ten measurements on only 4 patients pins down each patient’s mean precisely but still leaves you with just 4 independent units for the treatment question. General lesson: when ICC is high, add groups, not measurements per group. The demo in E5 shows it: with ICC 0.8 and a true difference of 1, the 4 × 10 design finds the difference in about 11% of studies, the 20 × 2 design in about 62%.
R1. Base-R reproduction:
shrink <- function(n, ybar, mu_hat = 6, sigma2 = 8, tau2 = 2) {
w <- (n / sigma2) / (n / sigma2 + 1 / tau2)
c(weight = w, estimate = w * ybar + (1 - w) * mu_hat)
}
shrink(n = 4, ybar = 10) # weight 0.5, estimate 8.0 (B3)
shrink(n = 1, ybar = 10) # weight 0.2, estimate 6.8 (B4)The \(n = 1\) group has the smaller weight (0.2 vs 0.5) and lands closer to the grand mean — more shrinkage, confirming B4.
R2.
icc <- function(sigma2, tau2) tau2 / (tau2 + sigma2)
icc(sigma2 = 8, tau2 = 2) # 0.2 (B5)
icc(sigma2 = 8, tau2 = 32) # 0.8\(\tau^2 = 32\) gives ICC \(= 0.8\): now 80% of variance is between groups, so grouping matters much more and the effective sample size is close to the number of groups.
R3. One Gaussian biomarker response per cell, with cells nested in patients:
lmer(biomarker ~ treatment + (1 | patient), data = d)
# Bayesian: brm(biomarker ~ treatment + (1 | patient), data = d)treatment is the fixed effect of interest; (1 | patient) gives each patient a random intercept, accounting for correlation between their cells. The residual represents variation between cells within a patient.
With repeated measurements per cell, add a cell-within-patient intercept:
lmer(biomarker ~ treatment + (1 | patient/cell), data = d)
# equivalently: biomarker ~ treatment + (1 | patient) + (1 | patient:cell)The repeats allow cell-level variance to be distinguished from residual variance; with only one response per cell those two variances are confounded.
Where this leads
- Penalized linear models: shrinkage here and ridge/lasso penalties there are the same idea from two angles — reining in extreme estimates. A random-effect variance \(\tau^2\) plays the role of a penalty strength that the data choose for you.
- Prior, likelihood, posterior (this block): “patient offsets scatter with spread \(\tau\)” is a prior on the group effects, with \(\tau\) estimated from the data — an adaptive prior. Hierarchical modelling is Bayesian inference with an extra layer.
- Error models (Poisson / negative binomial): real omics counts replace the Gaussian measurement noise with a count distribution; the hierarchical structure carries over unchanged, and overdispersion is itself a between-unit variance.