Pooling studies with a meta-analysis
Weigh thirteen vaccine trials into one estimate, see why the common-effect and random-effects answers differ, and read the prediction interval.
What runs in CodeSplash
- STAT279Cochran Q heterogeneity test Runs in CodeSplash
- Meta-analysis (pool studies, heterogeneity) Verified in Python and R
You will be able to
- Explain inverse-variance weighting in one sentence
- Tell a common-effect model from a random-effects model and say what each one estimates
- Read a pooled estimate, its confidence interval and its prediction interval
Read first
Thirteen trials, one question
ReadDoes the BCG vaccine prevent tuberculosis? Between 1948 and 1980, 13 trials tried to answer. Some found strong protection; others found almost none.
A meta-analysisMeta-analysisCombining several studies' estimates of the same effect into one weighted average, and asking how much they differ. combines such results into one estimate, weighted so that more precise studies count for more. It answers two questions, and the second matters as much as the first:
- What is the average effect?
- How much do the true effects differ from study to study?
Two models, one table
PredictPredict first
A common-effect model assumes every trial estimates the same number. A random-effects model lets each trial have its own true effect.
These trials disagree a lot. Which confidence interval do you expect to be wider?
Reveal
Common effect (Mantel–Haenszel): risk ratio 0.64, 95% CI 0.59 to 0.69.
Random effects: risk ratio 0.49, 95% CI 0.34 to 0.70.
Random effects is wider, because disagreement between trials is now part of the uncertainty.
Weighted by precision
ReadEach study gets an effect and a sampling variance . The pooled estimate is a weighted average:
In a common-effectCommon-effect modelAssumes every study estimates one shared true effect; differences are sampling error only. model , so a very large trial can dominate. In a random-effectsRandom-effects modelAssumes each study has its own true effect, drawn from a distribution whose mean is the pooled estimate and whose variance is τ². model, the between-study variance is added to every study's variance. That pulls the weights closer together, so small trials count for relatively more.
Ratios are pooled on the log scale and turned back afterwards.
Change the disagreement
ExploreAdd disagreement between studies and watch the forest plot. Notice which interval grows, and how the weights even out.
BExplorable · Forest plots and heterogeneity
When studies disagree, what does a pooled effect mean?
What share of the variation between studies is real (I²)?
Commit your prediction above to see the result
Make your prediction to see the result.
Then try the opposite: set the disagreement to zero. The two models should now agree closely.
Read the card
Readrisk ratio = 0.49, 95% CI [0.34, 0.70], p < .001; Q(12) = 152.23, p < .001, I² = 92.2%
- Pooled risk ratio
- 0.4894
- p
- < .001
- Cochran's Q
- 152.23
- p (heterogeneity)
- < .001
- τ²
- 0.3132
- I² (%)
- 92.221
Effect size
- Pooled risk ratio 0.4894 95% CI [0.3441, 0.6962]
Plots
View data
| risk ratio | high | row | study | low | weight % |
|---|---|---|---|---|---|
| 0.4109 | 1.257 | study | Aronson 1948 | 0.1343 | 5.059 |
| 0.2049 | 0.4864 | study | Ferguson & Simes 1949 | 0.0863 | 6.365 |
| 0.2597 | 0.9186 | study | Rosenthal et al 1960 | 0.0734 | 4.436 |
| 0.2366 | 0.3121 | study | Hart & Sutherland 1977 | 0.1793 | 9.699 |
| 0.8045 | 1.254 | study | Frimodt-Moller et al 1973 | 0.5163 | 8.868 |
| 0.4556 | 0.5362 | study | Stein & Aronson 1953 | 0.3871 | 10.096 |
| 0.1977 | 0.4989 | study | Vandiviere et al 1973 | 0.0784 | 6.027 |
| 1.012 | 1.145 | study | TPT Madras 1980 | 0.8946 | 10.189 |
| 0.6254 | 0.9962 | study | Coetzee & Berjak 1968 | 0.3926 | 8.743 |
| 0.2538 | 0.4310 | study | Rosenthal et al 1961 | 0.1494 | 8.368 |
| 0.7122 | 0.8860 | study | Comstock et al 1974 | 0.5725 | 9.925 |
| 1.562 | 6.528 | study | Comstock & Webster 1969 | 0.3737 | 3.822 |
| 0.9828 | 1.659 | study | Comstock et al 1976 | 0.5821 | 8.403 |
| 0.4894 | 0.6962 | summary | Pooled (RE) | 0.3441 | 100 |
View data
| log risk ratio | study | standard error |
|---|---|---|
| −0.8893 | Aronson 1948 | 0.5706 |
| −1.585 | Ferguson & Simes 1949 | 0.4411 |
| −1.348 | Rosenthal et al 1960 | 0.6445 |
| −1.442 | Hart & Sutherland 1977 | 0.1415 |
| −0.2175 | Frimodt-Moller et al 1973 | 0.2263 |
| −0.7861 | Stein & Aronson 1953 | 0.0831 |
| −1.621 | Vandiviere et al 1973 | 0.4722 |
| 0.0120 | TPT Madras 1980 | 0.0629 |
| −0.4694 | Coetzee & Berjak 1968 | 0.2376 |
| −1.371 | Rosenthal et al 1961 | 0.2702 |
| −0.3394 | Comstock et al 1974 | 0.1114 |
| 0.4459 | Comstock & Webster 1969 | 0.7297 |
| −0.0173 | Comstock et al 1976 | 0.2672 |
View data
| study | precision (1/SE) | standardized estimate |
|---|---|---|
| Aronson 1948 | 1.753 | −1.559 |
| Ferguson & Simes 1949 | 2.267 | −3.594 |
| Rosenthal et al 1960 | 1.552 | −2.092 |
| Hart & Sutherland 1977 | 7.069 | −10.191 |
| Frimodt-Moller et al 1973 | 4.419 | −0.9613 |
| Stein & Aronson 1953 | 12.034 | −9.460 |
| Vandiviere et al 1973 | 2.118 | −3.432 |
| TPT Madras 1980 | 15.888 | 0.1899 |
| Coetzee & Berjak 1968 | 4.209 | −1.976 |
| Rosenthal et al 1961 | 3.701 | −5.075 |
| Comstock et al 1974 | 8.976 | −3.046 |
| Comstock & Webster 1969 | 1.370 | 0.6111 |
| Comstock et al 1976 | 3.742 | −0.0648 |
View data
| study | risk, group 1 | risk, group 2 | participants |
|---|---|---|---|
| Aronson 1948 | 0.0325 | 0.0791 | 262 |
| Ferguson & Simes 1949 | 0.0196 | 0.0957 | 609 |
| Rosenthal et al 1960 | 0.0130 | 0.0500 | 451 |
| Hart & Sutherland 1977 | 0.0046 | 0.0193 | 26,465 |
| Frimodt-Moller et al 1973 | 0.0065 | 0.0081 | 10,877 |
| Stein & Aronson 1953 | 0.1168 | 0.2564 | 2,992 |
| Vandiviere et al 1973 | 0.0031 | 0.0159 | 3,174 |
| TPT Madras 1980 | 0.0057 | 0.0056 | 176,782 |
| Coetzee & Berjak 1968 | 0.0039 | 0.0062 | 14,776 |
| Rosenthal et al 1961 | 0.0099 | 0.0390 | 3,381 |
| Comstock et al 1974 | 0.0037 | 0.0052 | 77,972 |
| Comstock & Webster 1969 | 0.0020 | 0.0013 | 4,839 |
| Comstock et al 1976 | 0.0016 | 0.0016 | 34,767 |
Assumptions
- Enough studies — 13 studies.
- Heterogeneity — Q(12) = 152.23, p < .001; I² = 92.2%.
- Independent estimates — One estimate per study is assumed; several outcomes from one study need a multilevel model.
Studies (risk ratio, 95% CI)
| Study | Estimate | CI low | CI high | Weight % |
|---|---|---|---|---|
| Aronson 1948 | 0.4109 | 0.1343 | 1.257 | 5.059 |
| Ferguson & Simes 1949 | 0.2049 | 0.0863 | 0.4864 | 6.365 |
| Rosenthal et al 1960 | 0.2597 | 0.0734 | 0.9186 | 4.436 |
| Hart & Sutherland 1977 | 0.2366 | 0.1793 | 0.3121 | 9.699 |
| Frimodt-Moller et al 1973 | 0.8045 | 0.5163 | 1.254 | 8.868 |
| Stein & Aronson 1953 | 0.4556 | 0.3871 | 0.5362 | 10.096 |
| Vandiviere et al 1973 | 0.1977 | 0.0784 | 0.4989 | 6.027 |
| TPT Madras 1980 | 1.012 | 0.8946 | 1.145 | 10.189 |
| Coetzee & Berjak 1968 | 0.6254 | 0.3926 | 0.9962 | 8.743 |
| Rosenthal et al 1961 | 0.2538 | 0.1494 | 0.4310 | 8.368 |
| Comstock et al 1974 | 0.7122 | 0.5725 | 0.8860 | 9.925 |
| Comstock & Webster 1969 | 1.562 | 0.3737 | 6.528 | 3.822 |
| Comstock et al 1976 | 0.9828 | 0.5821 | 1.659 | 8.403 |
Heterogeneity
| Estimate | CI low | CI high | |
|---|---|---|---|
| τ² | 0.3132 | 0.1197 | 1.111 |
| τ | 0.5597 | 0.3460 | 1.054 |
| I² (%) | 92.221 | 81.921 | 97.678 |
| H² | 12.856 | — | — |
- Prediction interval for a new study's true effect: [0.134, 1.78].
- The z test ignores the uncertainty in τ²: with no effect it rejected 8.7% at the 5% level with 20 studies in simulation. Knapp–Hartung allows for it.
The exact R script · R R version 4.5.1 (2025-06-13)
# Meta-analysis (pool studies, heterogeneity)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.pool 1.0.3 · spec 6e902e32b28d2f2b
# Dataset: m1_bcg (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_meta_* (twins of codesplash.stats.meta)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/m1_bcg.parquet", col_select = c("trial", "events_1", "total_1", "events_2", "total_2")))
n_input <- nrow(df)
df[["trial"]] <- factor(df[["trial"]], levels = c("Aronson 1948", "Ferguson & Simes 1949", "Rosenthal et al 1960", "Hart & Sutherland 1977", "Frimodt-Moller et al 1973", "Stein & Aronson 1953", "Vandiviere et al 1973", "TPT Madras 1980", "Coetzee & Berjak 1968", "Rosenthal et al 1961", "Comstock et al 1974", "Comstock & Webster 1969", "Comstock et al 1976")) # stored level order
df <- df[stats::complete.cases(df[c("trial", "events_1", "total_1", "events_2", "total_2")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("trial", "events_1", "total_1", "events_2", "total_2")) # infinite values stop the run (registry/errors.yaml)
# %% Studies
design <- "binary" # inferred from the bound columns
measure <- "RR"
cols <- list(
events_1 = as.numeric(df[["events_1"]]),
total_1 = as.numeric(df[["total_1"]]),
events_2 = as.numeric(df[["events_2"]]),
total_2 = as.numeric(df[["total_2"]]),
NULL
)
cols <- Filter(Negate(is.null), cols)
es <- cs_meta_escalc(design, measure, cols, zero_cells = "only0", drop00 = TRUE, ci_level = 0.95)
measure <- es$measure
labels_all <- as.character(df[["trial"]])
keep <- es$keep
left_out <- labels_all[!keep]
idx <- which(keep)
y <- es$yi[idx]; v <- es$vi[idx]
labels <- labels_all[idx]
k <- length(y)
if (k < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A meta-analysis", min = 2, n = k) # one usable study can't be pooled
if (length(left_out)) {
warnings <- c(warnings, paste0(sprintf("Left out (%d): ", length(left_out)), paste(left_out, collapse = ", "),
if (design == "binary") " — no events (or only events) in both arms." else " — effect or variance not computable."))
}
bt <- cs_meta_back(measure)
MEASURE_LABEL <- c(GEN = "effect", LOG = "log ratio", OR = "log odds ratio", RR = "log risk ratio", RD = "risk difference",
MD = "mean difference", SMD = "Hedges' g", ZCOR = "Fisher's z", COR = "correlation")[[measure]]
RATIO <- measure %in% c("OR", "RR", "LOG")
# What a back-transformed number is: a ratio, not a log ratio; a correlation, not Fisher's z.
DISPLAY_LABEL <- if (measure %in% c("OR", "RR", "LOG", "ZCOR")) c(OR = "odds ratio", RR = "risk ratio", LOG = "ratio", ZCOR = "correlation")[[measure]] else MEASURE_LABEL
# %% Pool
conf <- 0.95
model <- "random"
pooling <- "inverse_variance"
if (pooling != "inverse_variance" && design != "binary") stop("Mantel–Haenszel and Peto pooling need two-arm counts.")
if (pooling == "peto") { measure <- "OR"; MEASURE_LABEL <- "Peto log odds ratio"; DISPLAY_LABEL <- "Peto odds ratio"; RATIO <- TRUE; bt <- exp }
fe <- cs_meta_rma(y, v, method = "FE")
if (pooling == "inverse_variance") {
fit <- cs_meta_rma(y, v, method = if (model == "fixed") "FE" else "REML", test = "z",
knha_trunc = FALSE, level = conf)
est <- fit$beta[1]; se <- fit$se[1]; stat <- fit$stat[1]; p <- fit$pval[1]
ci_low <- fit$ci_low[1]; ci_high <- fit$ci_high[1]
tau2 <- fit$tau2; q <- fit$qe; q_df <- fit$qe_df; q_p <- fit$qe_p
weights <- fit$weights
model_label <- if (model == "fixed") "common-effect model" else paste0("random effects, τ² by ", fit$method, if (fit$test == "knha") ", Knapp–Hartung t" else "")
} else {
a <- es$events_1[idx]; n1 <- es$total_1[idx]; c <- es$events_2[idx]; n2 <- es$total_2[idx]
pooled <- if (pooling == "mantel_haenszel") cs_meta_mh(a, n1, c, n2, measure, level = conf) else cs_meta_peto(a, n1, c, n2, level = conf)
est <- pooled$est; se <- pooled$se; stat <- pooled$z; p <- pooled$p
ci_low <- pooled$ci_low; ci_high <- pooled$ci_high
tau2 <- 0
if (pooling == "peto") {
q <- pooled$q; q_df <- pooled$q_df; q_p <- pooled$q_p
y <- pooled$yi; v <- pooled$vi
} else {
q <- fe$qe; q_df <- fe$qe_df; q_p <- fe$qe_p
}
weights <- (1 / v) / sum(1 / v) * 100
model_label <- if (pooling == "mantel_haenszel") "Mantel–Haenszel common effect" else "Peto common effect"
}
random_model <- pooling == "inverse_variance" && model == "random"
if (random_model) {
tci <- cs_meta_tau2_ci(y, v, level = conf); t_lo <- tci[1]; t_hi <- tci[2]
i2 <- fit$i2; h2 <- fit$h2
i2_lo <- cs_meta_i2(t_lo, fit$s2); i2_hi <- cs_meta_i2(t_hi, fit$s2)
pint <- cs_meta_pi(est, se, tau2, k, level = conf, dist = "t"); pi_low <- pint[1]; pi_high <- pint[2]
} else {
t_lo <- t_hi <- i2_lo <- i2_hi <- NaN
i2 <- if (q > 0) max(0, (q - q_df) / q * 100) else 0
h2 <- if (q_df > 0) q / q_df else NaN
pi_low <- ci_low; pi_high <- ci_high
}
zc <- stats::qnorm(1 - (1 - conf) / 2)
# %% Assumptions
assumptions <- list(
list(key = "k_studies", label = "Enough studies", status = if (k < 10 && random_model) "warn" else "pass",
detail = paste0(sprintf("%d studies", k), if (k < 10 && random_model) "; τ² and the prediction interval are imprecise — consider Knapp–Hartung inference." else ".")),
list(key = "heterogeneity", label = "Heterogeneity", status = if (q_p < 0.10 && !random_model) "warn" else "info",
detail = paste0(sprintf("Q(%d) = %.2f, %s; I² = %.1f%%", as.integer(q_df), q, cs_fmt_p(q_p), i2),
if (q_p < 0.10 && !random_model) "; a common-effect model ignores this — consider random effects." else ".")),
list(key = "independence", label = "Independent estimates", status = "info", detail = "One estimate per study is assumed; several outcomes from one study need a multilevel model.")
)
# %% Result
lo_i <- y - zc * sqrt(v); hi_i <- y + zc * sqrt(v)
study_rows <- lapply(seq_len(k), function(i) list(study = labels[i], estimate = bt(y[i]), low = bt(lo_i[i]), high = bt(hi_i[i]), weight = weights[i]))
summary_label <- paste0("Pooled (", if (random_model) "RE" else "CE", ")")
disp <- DISPLAY_LABEL
forest <- list(
label = cs_col("study", c(labels, summary_label)),
estimate = cs_col(disp, c(bt(y), bt(est))),
low = cs_col("low", c(bt(lo_i), bt(ci_low))),
high = cs_col("high", c(bt(hi_i), bt(ci_high))),
weight = cs_col("weight %", c(weights, 100)),
kind = cs_col("row", c(rep("study", k), "summary"))
)
fcontrols <- list(reference = if (RATIO) 1 else 0, log = RATIO)
if (random_model) { fcontrols$piLow <- bt(pi_low); fcontrols$piHigh <- bt(pi_high) }
charts <- list(
cs_chart("forest", "forest-meta", "Studies and the pooled estimate", forest, controls = fcontrols),
cs_chart("funnel", "meta-funnel", "Funnel plot", list(estimate = cs_col(MEASURE_LABEL, y), se = cs_col("standard error", sqrt(v)), label = cs_col("study", labels)),
controls = list(center = est, contours = TRUE)),
cs_chart("galbraith", "galbraith", "Radial (Galbraith) plot", list(z = cs_col("standardized estimate", y / sqrt(v)), precision = cs_col("precision (1/SE)", 1 / sqrt(v)),
label = cs_col("study", labels)), controls = list(slope = fe$beta[1]))
)
if (design == "binary") {
a <- es$events_1[idx]; n1 <- es$total_1[idx]; c <- es$events_2[idx]; n2 <- es$total_2[idx]
charts[[length(charts) + 1]] <- cs_chart("labbe", "labbe", "L'Abbé plot: event risk in each arm",
list(risk_1 = cs_col("risk, group 1", a / n1), risk_2 = cs_col("risk, group 2", c / n2), weight = cs_col("participants", n1 + n2), label = cs_col("study", labels)))
}
pct <- sprintf("%.0f%%", conf * 100)
na_or <- function(x) if (is.na(x)) NULL else x
cs_publish(list(
method = "meta.pool",
methodVersion = "1.0.3",
title = sprintf("Meta-analysis of %d studies (%s)", k, model_label),
engine = cs_engine_info("stats", "nanoparquet"),
n = k,
summary = sprintf("Pooled %s %s, %s CI [%s, %s], %s; Q(%d) = %.2f, %s, I² = %.1f%%.", disp, format(signif(bt(est), 3)), pct,
format(signif(bt(ci_low), 3)), format(signif(bt(ci_high), 3)), cs_fmt_p(p), as.integer(q_df), q, cs_fmt_p(q_p), i2),
apa = sprintf("%s = %s, %s CI [%s, %s], %s; Q(%d) = %s, %s, I² = %.1f%%", disp, cs_fmt_num(bt(est)), pct, cs_fmt_num(bt(ci_low)), cs_fmt_num(bt(ci_high)),
cs_fmt_p(p), as.integer(q_df), cs_fmt_num(q), cs_fmt_p(q_p), i2),
statistics = list(
list(key = "est_bt", label = paste0("Pooled ", disp), value = bt(est)),
list(key = "p", label = "p", value = p, format = "p"),
list(key = "q", label = "Cochran's Q", value = q), list(key = "q_p", label = "p (heterogeneity)", value = q_p, format = "p"),
list(key = "tau2", label = "τ²", value = tau2), list(key = "i2", label = "I² (%)", value = i2)
),
tables = list(
list(key = "studies", title = sprintf("Studies (%s, %s CI)", disp, pct),
columns = list(list(key = "study", label = "Study", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
list(key = "low", label = "CI low", type = "number"), list(key = "high", label = "CI high", type = "number"),
list(key = "weight", label = "Weight %", type = "number")),
rows = study_rows),
list(key = "heterogeneity", title = "Heterogeneity",
columns = list(list(key = "quantity", label = "", type = "string"), list(key = "value", label = "Estimate", type = "number"),
list(key = "low", label = "CI low", type = "number"), list(key = "high", label = "CI high", type = "number")),
rows = list(list(quantity = "τ²", value = tau2, low = na_or(t_lo), high = na_or(t_hi)),
list(quantity = "τ", value = sqrt(tau2), low = na_or(sqrt(t_lo)), high = na_or(sqrt(t_hi))),
list(quantity = "I² (%)", value = i2, low = na_or(i2_lo), high = na_or(i2_hi)),
list(quantity = "H²", value = h2, low = NULL, high = NULL)))
),
effectSizes = list(list(key = "est_bt", label = paste0("Pooled ", disp), value = bt(est), ciLow = bt(ci_low), ciHigh = bt(ci_high), ciLevel = conf,
method = model_label)),
assumptions = assumptions,
warnings = warnings,
notes = c(list(if (random_model) sprintf("Prediction interval for a new study's true effect: [%s, %s].", format(signif(bt(pi_low), 3)), format(signif(bt(pi_high), 3)))
else "Common-effect model: the interval describes these studies only."),
if (random_model && fit$test != "knha") list("The z test ignores the uncertainty in τ²: with no effect it rejected 8.7% at the 5% level with 20 studies in simulation. Knapp–Hartung allows for it.")),
charts = charts,
values = list(
k = k, k_left_out = length(left_out), est = est, se = se, stat = stat, p = p, ci_low = ci_low, ci_high = ci_high,
est_bt = bt(est), ci_low_bt = bt(ci_low), ci_high_bt = bt(ci_high),
tau2 = tau2, tau = sqrt(tau2), tau2_ci_low = t_lo, tau2_ci_high = t_hi, i2 = i2, i2_ci_low = i2_lo, i2_ci_high = i2_hi, h2 = h2,
q = q, q_df = q_df, q_p = q_p, pi_low = pi_low, pi_high = pi_high, pi_low_bt = bt(pi_low), pi_high_bt = bt(pi_high),
measure = measure, measure_label = MEASURE_LABEL, effect_label = disp, model_label = model_label
)
))
risk ratio = 0.49, 95% CI [0.34, 0.70], p < .001; Q(12) = 152.23, p < .001, I² = 92.2%
- Pooled risk ratio
- 0.4894
- p
- < .001
- Cochran's Q
- 152.23
- p (heterogeneity)
- < .001
- τ²
- 0.3132
- I² (%)
- 92.221
Effect size
- Pooled risk ratio 0.4894 95% CI [0.3441, 0.6962]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough studies — 13 studies.
- Heterogeneity — Q(12) = 152.23, p < .001; I² = 92.2%.
- Independent estimates — One estimate per study is assumed; several outcomes from one study need a multilevel model.
Studies (risk ratio, 95% CI)
| Study | Estimate | CI low | CI high | Weight % |
|---|---|---|---|---|
| Aronson 1948 | 0.4109 | 0.1343 | 1.257 | 5.059 |
| Ferguson & Simes 1949 | 0.2049 | 0.0863 | 0.4864 | 6.365 |
| Rosenthal et al 1960 | 0.2597 | 0.0734 | 0.9186 | 4.436 |
| Hart & Sutherland 1977 | 0.2366 | 0.1793 | 0.3121 | 9.699 |
| Frimodt-Moller et al 1973 | 0.8045 | 0.5163 | 1.254 | 8.868 |
| Stein & Aronson 1953 | 0.4556 | 0.3871 | 0.5362 | 10.096 |
| Vandiviere et al 1973 | 0.1977 | 0.0784 | 0.4989 | 6.027 |
| TPT Madras 1980 | 1.012 | 0.8946 | 1.145 | 10.189 |
| Coetzee & Berjak 1968 | 0.6254 | 0.3926 | 0.9962 | 8.743 |
| Rosenthal et al 1961 | 0.2538 | 0.1494 | 0.4310 | 8.368 |
| Comstock et al 1974 | 0.7122 | 0.5725 | 0.8860 | 9.925 |
| Comstock & Webster 1969 | 1.562 | 0.3737 | 6.528 | 3.822 |
| Comstock et al 1976 | 0.9828 | 0.5821 | 1.659 | 8.403 |
Heterogeneity
| Estimate | CI low | CI high | |
|---|---|---|---|
| τ² | 0.3132 | 0.1197 | 1.111 |
| τ | 0.5597 | 0.3460 | 1.054 |
| I² (%) | 92.221 | 81.921 | 97.678 |
| H² | 12.856 | — | — |
- Prediction interval for a new study's true effect: [0.134, 1.78].
- The z test ignores the uncertainty in τ²: with no effect it rejected 8.7% at the 5% level with 20 studies in simulation. Knapp–Hartung allows for it.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Meta-analysis (pool studies, heterogeneity)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.pool 1.0.3 · spec 6e902e32b28d2f2b
# Dataset: m1_bcg (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import meta # twins of codesplashr::cs_meta_*
# %% Data
df = pd.read_parquet("tests/parity/fixtures/m1_bcg.parquet", columns=["trial", "events_1", "total_1", "events_2", "total_2"])
n_input = len(df)
df["trial"] = pd.Categorical(df["trial"], categories=["Aronson 1948", "Ferguson & Simes 1949", "Rosenthal et al 1960", "Hart & Sutherland 1977", "Frimodt-Moller et al 1973", "Stein & Aronson 1953", "Vandiviere et al 1973", "TPT Madras 1980", "Coetzee & Berjak 1968", "Rosenthal et al 1961", "Comstock et al 1974", "Comstock & Webster 1969", "Comstock et al 1976"]) # stored level order
df = df.dropna(subset=["trial", "events_1", "total_1", "events_2", "total_2"]) # listwise deletion over the analysis columns
df["trial"] = df["trial"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["trial", "events_1", "total_1", "events_2", "total_2"]) # infinite values stop the run (registry/errors.yaml)
# %% Studies
design = "binary" # inferred from the bound columns
measure = "RR"
cols = {
"events_1": df["events_1"].to_numpy(dtype=float),
"total_1": df["total_1"].to_numpy(dtype=float),
"events_2": df["events_2"].to_numpy(dtype=float),
"total_2": df["total_2"].to_numpy(dtype=float),
}
es = meta.escalc(design, measure, cols, zero_cells="only0", drop00=True, ci_level=0.95)
measure = es["measure"]
labels_all = df["trial"].astype(str).tolist()
keep = es["keep"]
left_out = [labels_all[i] for i in np.flatnonzero(~keep)]
idx = np.flatnonzero(keep)
y, v = es["yi"][idx], es["vi"][idx]
labels = [labels_all[i] for i in idx]
k = len(y)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A meta-analysis", min=2, n=k) # one usable study can't be pooled
if left_out:
warnings.append(f"Left out ({len(left_out)}): " + ", ".join(left_out) + (" — no events (or only events) in both arms." if design == "binary" else " — effect or variance not computable."))
bt = meta.back_transform(measure)
MEASURE_LABEL = {"GEN": "effect", "LOG": "log ratio", "OR": "log odds ratio", "RR": "log risk ratio", "RD": "risk difference",
"MD": "mean difference", "SMD": "Hedges' g", "ZCOR": "Fisher's z", "COR": "correlation"}[measure]
RATIO = measure in ("OR", "RR", "LOG")
# What a back-transformed number is: a ratio, not a log ratio; a correlation, not Fisher's z.
DISPLAY_LABEL = {"OR": "odds ratio", "RR": "risk ratio", "LOG": "ratio", "ZCOR": "correlation"}.get(measure, MEASURE_LABEL)
# %% Pool
conf = 0.95
model = "random"
pooling = "inverse_variance"
if pooling != "inverse_variance" and design != "binary":
raise ValueError("Mantel–Haenszel and Peto pooling need two-arm counts.")
if pooling == "peto":
measure, MEASURE_LABEL, DISPLAY_LABEL, RATIO, bt = "OR", "Peto log odds ratio", "Peto odds ratio", True, np.exp
fe = meta.rma(y, v, method="FE")
if pooling == "inverse_variance":
fit = meta.rma(y, v, method="FE" if model == "fixed" else "REML", test="z",
knha_trunc=False, level=conf)
est, se, stat, p = float(fit["beta"][0]), float(fit["se"][0]), float(fit["stat"][0]), float(fit["pval"][0])
ci_low, ci_high = float(fit["ci_low"][0]), float(fit["ci_high"][0])
tau2, q, q_df, q_p = fit["tau2"], fit["qe"], fit["qe_df"], fit["qe_p"]
weights = fit["weights"]
model_label = "common-effect model" if model == "fixed" else f"random effects, τ² by {fit['method']}" + (", Knapp–Hartung t" if fit["test"] == "knha" else "")
else:
a, n1, c, n2 = (es[key][idx] for key in ("events_1", "total_1", "events_2", "total_2"))
pooled = meta.mantel_haenszel(a, n1, c, n2, measure, level=conf) if pooling == "mantel_haenszel" else meta.peto(a, n1, c, n2, level=conf)
est, se, stat, p = pooled["est"], pooled["se"], pooled["z"], pooled["p"]
ci_low, ci_high = pooled["ci_low"], pooled["ci_high"]
tau2 = 0.0
if pooling == "peto":
q, q_df, q_p = pooled["q"], pooled["q_df"], pooled["q_p"]
y, v = pooled["yi"], pooled["vi"]
else:
q, q_df, q_p = fe["qe"], fe["qe_df"], fe["qe_p"]
weights = (1 / v) / np.sum(1 / v) * 100
model_label = "Mantel–Haenszel common effect" if pooling == "mantel_haenszel" else "Peto common effect"
random_model = pooling == "inverse_variance" and model == "random"
if random_model:
t_lo, t_hi = meta.tau2_ci(y, v, level=conf)
i2, h2 = fit["i2"], fit["h2"]
i2_lo, i2_hi = meta.i2_from_tau2(t_lo, fit["s2"]), meta.i2_from_tau2(t_hi, fit["s2"])
pi_low, pi_high = meta.prediction_interval(est, se, tau2, k, level=conf, dist="t")
else:
t_lo = t_hi = i2_lo = i2_hi = float("nan")
i2 = max(0.0, (q - q_df) / q * 100) if q > 0 else 0.0 # Higgins & Thompson from Q
h2 = q / q_df if q_df > 0 else float("nan")
pi_low, pi_high = ci_low, ci_high
zc = float(stats.norm.ppf(1 - (1 - conf) / 2))
# %% Assumptions
assumptions = [
{"key": "k_studies", "label": "Enough studies", "status": "warn" if k < 10 and random_model else "pass",
"detail": f"{k} studies" + ("; τ² and the prediction interval are imprecise — consider Knapp–Hartung inference." if k < 10 and random_model else ".")},
{"key": "heterogeneity", "label": "Heterogeneity", "status": "warn" if q_p < 0.10 and not random_model else "info",
"detail": f"Q({q_df}) = {q:.2f}, {cs.fmt_p(q_p)}; I² = {i2:.1f}%" + ("; a common-effect model ignores this — consider random effects." if q_p < 0.10 and not random_model else ".")},
{"key": "independence", "label": "Independent estimates", "status": "info", "detail": "One estimate per study is assumed; several outcomes from one study need a multilevel model."},
]
# %% Result
lo_i, hi_i = y - zc * np.sqrt(v), y + zc * np.sqrt(v)
study_rows = [{"study": labels[i], "estimate": float(bt(y[i])), "low": float(bt(lo_i[i])), "high": float(bt(hi_i[i])), "weight": float(weights[i])} for i in range(k)]
summary_label = "Pooled (" + ("RE" if random_model else "CE") + ")"
forest = {
"label": cs.col("study", labels + [summary_label]),
"estimate": cs.col(DISPLAY_LABEL, [r["estimate"] for r in study_rows] + [float(bt(est))]),
"low": cs.col("low", [r["low"] for r in study_rows] + [float(bt(ci_low))]),
"high": cs.col("high", [r["high"] for r in study_rows] + [float(bt(ci_high))]),
"weight": cs.col("weight %", [r["weight"] for r in study_rows] + [100.0]),
"kind": cs.col("row", ["study"] * k + ["summary"]),
}
charts = [
cs.chart("forest", "forest-meta", "Studies and the pooled estimate", forest,
controls={"reference": 1 if RATIO else 0, "log": RATIO, **({"piLow": float(bt(pi_low)), "piHigh": float(bt(pi_high))} if random_model else {})}),
cs.chart("funnel", "meta-funnel", "Funnel plot", {"estimate": cs.col(MEASURE_LABEL, [float(t) for t in y]), "se": cs.col("standard error", [float(t) for t in np.sqrt(v)]),
"label": cs.col("study", labels)},
controls={"center": est, "contours": True}),
cs.chart("galbraith", "galbraith", "Radial (Galbraith) plot", {"z": cs.col("standardized estimate", [float(t) for t in y / np.sqrt(v)]),
"precision": cs.col("precision (1/SE)", [float(t) for t in 1 / np.sqrt(v)]), "label": cs.col("study", labels)},
controls={"slope": float(fe["beta"][0])}),
]
if design == "binary":
a, n1, c, n2 = (es[key][idx] for key in ("events_1", "total_1", "events_2", "total_2"))
charts.append(cs.chart("labbe", "labbe", "L'Abbé plot: event risk in each arm",
{"risk_1": cs.col("risk, group 1", [float(t) for t in a / n1]), "risk_2": cs.col("risk, group 2", [float(t) for t in c / n2]),
"weight": cs.col("participants", [float(t) for t in n1 + n2]), "label": cs.col("study", labels)}))
nan = lambda x: None if x is None or (isinstance(x, float) and math.isnan(x)) else x # noqa: E731
cs.publish({
"method": "meta.pool",
"methodVersion": "1.0.3",
"title": f"Meta-analysis of {k} studies ({model_label})",
"engine": cs.engine_info("numpy", "scipy"),
"n": k,
"summary": f"Pooled {DISPLAY_LABEL} {bt(est):.3g}, {conf:.0%} CI [{bt(ci_low):.3g}, {bt(ci_high):.3g}], {cs.fmt_p(p)}; Q({q_df}) = {q:.2f}, {cs.fmt_p(q_p)}, I² = {i2:.1f}%.",
"apa": f"{DISPLAY_LABEL} = {cs.fmt_num(float(bt(est)))}, {conf:.0%} CI [{cs.fmt_num(float(bt(ci_low)))}, {cs.fmt_num(float(bt(ci_high)))}], {cs.fmt_p(p)}; Q({q_df}) = {cs.fmt_num(q)}, {cs.fmt_p(q_p)}, I² = {i2:.1f}%",
"statistics": [
{"key": "est_bt", "label": "Pooled " + DISPLAY_LABEL, "value": float(bt(est))},
{"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "q", "label": "Cochran's Q", "value": q}, {"key": "q_p", "label": "p (heterogeneity)", "value": q_p, "format": "p"},
{"key": "tau2", "label": "τ²", "value": tau2}, {"key": "i2", "label": "I² (%)", "value": i2},
],
"tables": [
{"key": "studies", "title": f"Studies ({DISPLAY_LABEL}, {conf:.0%} CI)",
"columns": [{"key": "study", "label": "Study", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
{"key": "low", "label": "CI low", "type": "number"}, {"key": "high", "label": "CI high", "type": "number"},
{"key": "weight", "label": "Weight %", "type": "number"}],
"rows": study_rows},
{"key": "heterogeneity", "title": "Heterogeneity",
"columns": [{"key": "quantity", "label": "", "type": "string"}, {"key": "value", "label": "Estimate", "type": "number"},
{"key": "low", "label": "CI low", "type": "number"}, {"key": "high", "label": "CI high", "type": "number"}],
"rows": [{"quantity": "τ²", "value": tau2, "low": nan(t_lo), "high": nan(t_hi)}, {"quantity": "τ", "value": math.sqrt(tau2), "low": nan(math.sqrt(t_lo) if t_lo == t_lo else t_lo), "high": nan(math.sqrt(t_hi) if t_hi == t_hi else t_hi)},
{"quantity": "I² (%)", "value": i2, "low": nan(i2_lo), "high": nan(i2_hi)}, {"quantity": "H²", "value": h2, "low": None, "high": None}]},
],
"effectSizes": [{"key": "est_bt", "label": "Pooled " + DISPLAY_LABEL, "value": float(bt(est)), "ciLow": float(bt(ci_low)), "ciHigh": float(bt(ci_high)), "ciLevel": conf,
"method": model_label}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Prediction interval for a new study's true effect: [{bt(pi_low):.3g}, {bt(pi_high):.3g}]." if random_model else "Common-effect model: the interval describes these studies only."] + (["The z test ignores the uncertainty in τ²: with no effect it rejected 8.7% at the 5% level with 20 studies in simulation. Knapp–Hartung allows for it."] if random_model and fit["test"] != "knha" else []),
"charts": charts,
"values": {
"k": k, "k_left_out": len(left_out), "est": est, "se": se, "stat": stat, "p": p, "ci_low": ci_low, "ci_high": ci_high,
"est_bt": float(bt(est)), "ci_low_bt": float(bt(ci_low)), "ci_high_bt": float(bt(ci_high)),
"tau2": tau2, "tau": math.sqrt(tau2), "tau2_ci_low": t_lo, "tau2_ci_high": t_hi, "i2": i2, "i2_ci_low": i2_lo, "i2_ci_high": i2_hi, "h2": h2,
"q": q, "q_df": float(q_df), "q_p": q_p, "pi_low": pi_low, "pi_high": pi_high, "pi_low_bt": float(bt(pi_low)), "pi_high_bt": float(bt(pi_high)),
"measure": measure, "measure_label": MEASURE_LABEL, "effect_label": DISPLAY_LABEL, "model_label": model_label,
},
})
The pooled risk ratio is 0.49: on average, vaccinated people had about half the risk.
The card also gives a prediction intervalPrediction interval (meta-analysis)Where the true effect of a new, comparable study would be expected to fall — wider than the CI of the mean whenever τ² > 0.: 0.13 to 1.78. That is the range expected for the true effect in a new setting. It crosses 1, so a new setting could see no benefit at all, even though the average favors the vaccine.
Which interval answers which question?
ReflectThe confidence interval is about the average. The prediction interval is about a new study.
Suppose you run a vaccination program in one new region. Which interval do you report to its health director, and why? Say your answer out loud before moving on.
Check your understanding
CheckpointCheck yourself
Adding to each study's variance has what effect on the weights?
Show the answer
Answer: b
Each weight is . A large swamps the differences in , so the weights even out, though they stay unequal unless every is the same.
Check yourself
A pooled risk ratio has a 95% CI that excludes 1 and a 95% prediction interval that includes 1. Which statement fits?
Show the answer
Answer: a
They answer different questions. The confidence interval describes the mean of the true effects; the prediction interval also includes how widely those effects vary.
Check yourself
How many trials went into the pooled BCG estimate on the card?
Show the answer
Answer: 13
The card reports k, the number of studies pooled.
Do it in CodeSplash
In the appOpen Studios, choose Meta-analysis, and start from Pool study results. The walkthrough takes the BCG table, one row per {{study}}, from effect sizes to a pooled result.
For a quick run in Analyze, start here:
The calculation in code
In the appThis script pools the log odds ratios with the DerSimonian–Laird . The result matches the bcg-or-dl-knha example's estimate of 0.474.
import numpy as np
import pandas as pd
d = pd.read_csv("m1_bcg.csv")
a, c = d.events_1, d.events_2
b, e = d.total_1 - a, d.total_2 - c
y = np.log(a * e / (b * c)) # log odds ratio
v = 1 / a + 1 / b + 1 / c + 1 / e
w = 1 / v
q = np.sum(w * (y - np.sum(w * y) / w.sum()) ** 2)
tau2 = max(0, (q - (len(y) - 1)) / (w.sum() - np.sum(w ** 2) / w.sum()))
w_re = 1 / (v + tau2)
print(np.exp(np.sum(w_re * y) / w_re.sum()), tau2, q)d <- read.csv("m1_bcg.csv")
a <- d$events_1; c <- d$events_2
b <- d$total_1 - a; e <- d$total_2 - c
y <- log(a * e / (b * c)) # log odds ratio
v <- 1 / a + 1 / b + 1 / c + 1 / e
w <- 1 / v
q <- sum(w * (y - sum(w * y) / sum(w))^2)
tau2 <- max(0, (q - (length(y) - 1)) / (sum(w) - sum(w^2) / sum(w)))
w_re <- 1 / (v + tau2)
c(exp(sum(w_re * y) / sum(w_re)), tau2, q)Recap
Recap- A meta-analysis is a precision-weighted average of study effects.
- Common effect assumes one true effect. Random effects estimates the mean of a distribution of true effects.
- The confidence interval describes that mean. The prediction interval describes what a new setting might see.
Concepts in this lesson