How much do the studies disagree?
Read Cochran's Q, I², τ² and the Knapp–Hartung adjustment, and learn which of them answers "how much do the effects vary?"
What runs in CodeSplash
- STAT279Cochran Q heterogeneity test Runs in CodeSplash
- STAT280Knapp–Hartung meta regression tests Runs in CodeSplash
- Meta-analysis (pool studies, heterogeneity) Verified in Python and R
You will be able to
- Say what Cochran's Q tests and why a non-significant Q does not show agreement
- Tell I² apart from τ² and pick the one that answers your question
- Explain what the Knapp–Hartung adjustment changes and when to use it
Read first
Three numbers people mix up
ReadFor the BCG trials, the card reports:
- Cochran's QCochran's QThe weighted sum of squared deviations of study estimates from the common-effect estimate; χ² with k − 1 df if all studies share one effect. = 152.2 on 12 df, p < .001. A test: is there any variation beyond sampling error?
- I²I² (inconsistency)The share of the variation in study estimates that comes from real differences between studies rather than sampling error. = 92.2%. A share: how much of the observed variation is not sampling error?
- τ²Between-study variance (τ²)How much the studies' true effects vary around their mean; τ is the same on the effect's own scale. = 0.313. A size: how much do true effects vary, in squared log risk ratio units?
Same I², different story
PredictPredict first
Meta-analysis A pools huge trials and has I² = 80%. Meta-analysis B pools tiny trials and also has I² = 80%.
In which one do the true effects vary more?
Reveal
You cannot tell. I² compares between-study variation to sampling error. Huge trials have tiny sampling error, so even trivial real variation gives a high I². Report τ, or better the prediction interval, to say how much effects actually vary.
Watch Q and I² respond
ExploreChange the number of studies and how much the true effects differ. Keep an eye on when Q reaches significance and how I² behaves with few studies.
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.
The anatomy below shows how Q is computed from weighted squared deviations.
BExplorable · Cochran Q heterogeneity test
Do the studies estimate one common effect?
Adds bias × SE: small studies report bigger effects.
Your data
Simulated with a known ρIf H₀ were true
- The reference: how Q varies across samples when H₀ is true.
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .517).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- study effects and standard errors
- fixed-effect pooled estimate
The verdict
Q(13) = 12.13, p = .517, I² = 0.00
p > α = .050: compatible with H₀
Effect size: share of variation beyond chance I² = 0.000
Low power with few studies, over-sensitive with many: report I² and τ² with intervals rather than the Q test alone.
- Statistic
- 12.125
- p-value
- 0.5174
Cochran Q heterogeneity test on 14 (x, y) pairs: Q(13) = 12.13, p = .517, I² = 0.00. The p-value is above α = .050, so the data are compatible with H₀.
A quiet Q is not agreement
ReadThe guide's example has 12 studies, with Q = 5.53, p = .903 and I² = 0%.
Read the interval too. I² runs up to 36%, so these data are compatible with moderate heterogeneity. Q has low power with few studies, which is why you should not use it to choose between models.
effect = 0.09, 95% CI [−0.02, 0.19], p = .121; Q(11) = 5.53, p = .903, I² = 0.0%
- Pooled effect
- 0.0856
- p
- .121
- Cochran's Q
- 5.530
- p (heterogeneity)
- .903
- τ²
- 0
- I² (%)
- 0
Effect size
- Pooled effect 0.0856 95% CI [−0.0226, 0.1937]
Plots
View data
| effect | high | row | study | low | weight % |
|---|---|---|---|---|---|
| 0.3041 | 0.7187 | study | Study 01 | −0.1105 | 6.800 |
| −0.0159 | 0.3299 | study | Study 02 | −0.3618 | 9.773 |
| 0.2278 | 0.6420 | study | Study 03 | −0.1863 | 6.815 |
| 0.1831 | 0.5134 | study | Study 04 | −0.1473 | 10.711 |
| 0.0667 | 0.3461 | study | Study 05 | −0.2128 | 14.968 |
| −0.3032 | 0.1610 | study | Study 06 | −0.7675 | 5.423 |
| 0.0530 | 0.5885 | study | Study 07 | −0.4826 | 4.075 |
| −0.0040 | 0.3384 | study | Study 08 | −0.3464 | 9.968 |
| 0.2227 | 0.7180 | study | Study 09 | −0.2726 | 4.763 |
| 0.1052 | 0.3891 | study | Study 10 | −0.1786 | 14.509 |
| 0.1184 | 0.5787 | study | Study 11 | −0.3420 | 5.515 |
| 0.0539 | 0.4722 | study | Study 12 | −0.3644 | 6.679 |
| 0.0856 | 0.1937 | summary | Pooled (RE) | −0.0226 | 100 |
View data
| effect | study | standard error |
|---|---|---|
| 0.3041 | Study 01 | 0.2115 |
| −0.0159 | Study 02 | 0.1764 |
| 0.2278 | Study 03 | 0.2113 |
| 0.1831 | Study 04 | 0.1685 |
| 0.0667 | Study 05 | 0.1426 |
| −0.3032 | Study 06 | 0.2369 |
| 0.0530 | Study 07 | 0.2732 |
| −0.0040 | Study 08 | 0.1747 |
| 0.2227 | Study 09 | 0.2527 |
| 0.1052 | Study 10 | 0.1448 |
| 0.1184 | Study 11 | 0.2349 |
| 0.0539 | Study 12 | 0.2134 |
View data
| study | precision (1/SE) | standardized estimate |
|---|---|---|
| Study 01 | 4.728 | 1.438 |
| Study 02 | 5.668 | −0.0903 |
| Study 03 | 4.733 | 1.078 |
| Study 04 | 5.933 | 1.086 |
| Study 05 | 7.014 | 0.4676 |
| Study 06 | 4.222 | −1.280 |
| Study 07 | 3.660 | 0.1939 |
| Study 08 | 5.724 | −0.0230 |
| Study 09 | 3.957 | 0.8812 |
| Study 10 | 6.906 | 0.7268 |
| Study 11 | 4.258 | 0.5039 |
| Study 12 | 4.686 | 0.2526 |
Assumptions
- Enough studies — 12 studies.
- Heterogeneity — Q(11) = 5.53, p = .903; I² = 0.0%.
- Independent estimates — One estimate per study is assumed; several outcomes from one study need a multilevel model.
Studies (effect, 95% CI)
| Study | Estimate | CI low | CI high | Weight % |
|---|---|---|---|---|
| Study 01 | 0.3041 | −0.1105 | 0.7187 | 6.800 |
| Study 02 | −0.0159 | −0.3618 | 0.3299 | 9.773 |
| Study 03 | 0.2278 | −0.1863 | 0.6420 | 6.815 |
| Study 04 | 0.1831 | −0.1473 | 0.5134 | 10.711 |
| Study 05 | 0.0667 | −0.2128 | 0.3461 | 14.968 |
| Study 06 | −0.3032 | −0.7675 | 0.1610 | 5.423 |
| Study 07 | 0.0530 | −0.4826 | 0.5885 | 4.075 |
| Study 08 | −0.0040 | −0.3464 | 0.3384 | 9.968 |
| Study 09 | 0.2227 | −0.2726 | 0.7180 | 4.763 |
| Study 10 | 0.1052 | −0.1786 | 0.3891 | 14.509 |
| Study 11 | 0.1184 | −0.3420 | 0.5787 | 5.515 |
| Study 12 | 0.0539 | −0.3644 | 0.4722 | 6.679 |
Heterogeneity
| Estimate | CI low | CI high | |
|---|---|---|---|
| τ² | 0 | 0 | 0.0211 |
| τ | 0 | 0 | 0.1452 |
| I² (%) | 0 | 0 | 36.243 |
| H² | 1 | — | — |
- Prediction interval for a new study's true effect: [-0.0373, 0.208].
- 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 1bb4f028aa869674
# Dataset: m1_guide (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_guide.parquet", col_select = c("study", "effect", "se")))
n_input <- nrow(df)
df[["study"]] <- factor(df[["study"]], levels = c("Study 01", "Study 02", "Study 03", "Study 04", "Study 05", "Study 06", "Study 07", "Study 08", "Study 09", "Study 10", "Study 11", "Study 12")) # stored level order
df <- df[stats::complete.cases(df[c("study", "effect", "se")]), , 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("study", "effect", "se")) # infinite values stop the run (registry/errors.yaml)
# %% Studies
design <- "generic" # inferred from the bound columns
measure <- "GEN"
cols <- list(
effect = as.numeric(df[["effect"]]),
se = as.numeric(df[["se"]]),
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[["study"]])
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
)
))
effect = 0.09, 95% CI [−0.02, 0.19], p = .121; Q(11) = 5.53, p = .903, I² = 0.0%
- Pooled effect
- 0.0856
- p
- .121
- Cochran's Q
- 5.530
- p (heterogeneity)
- .903
- τ²
- 0
- I² (%)
- 0
Effect size
- Pooled effect 0.0856 95% CI [−0.0226, 0.1937]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough studies — 12 studies.
- Heterogeneity — Q(11) = 5.53, p = .903; I² = 0.0%.
- Independent estimates — One estimate per study is assumed; several outcomes from one study need a multilevel model.
Studies (effect, 95% CI)
| Study | Estimate | CI low | CI high | Weight % |
|---|---|---|---|---|
| Study 01 | 0.3041 | −0.1105 | 0.7187 | 6.800 |
| Study 02 | −0.0159 | −0.3618 | 0.3299 | 9.773 |
| Study 03 | 0.2278 | −0.1863 | 0.6420 | 6.815 |
| Study 04 | 0.1831 | −0.1473 | 0.5134 | 10.711 |
| Study 05 | 0.0667 | −0.2128 | 0.3461 | 14.968 |
| Study 06 | −0.3032 | −0.7675 | 0.1610 | 5.423 |
| Study 07 | 0.0530 | −0.4826 | 0.5885 | 4.075 |
| Study 08 | −0.0040 | −0.3464 | 0.3384 | 9.968 |
| Study 09 | 0.2227 | −0.2726 | 0.7180 | 4.763 |
| Study 10 | 0.1052 | −0.1786 | 0.3891 | 14.509 |
| Study 11 | 0.1184 | −0.3420 | 0.5787 | 5.515 |
| Study 12 | 0.0539 | −0.3644 | 0.4722 | 6.679 |
Heterogeneity
| Estimate | CI low | CI high | |
|---|---|---|---|
| τ² | 0 | 0 | 0.0211 |
| τ | 0 | 0 | 0.1452 |
| I² (%) | 0 | 0 | 36.243 |
| H² | 1 | — | — |
- Prediction interval for a new study's true effect: [-0.0373, 0.208].
- 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 1bb4f028aa869674
# Dataset: m1_guide (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_guide.parquet", columns=["study", "effect", "se"])
n_input = len(df)
df["study"] = pd.Categorical(df["study"], categories=["Study 01", "Study 02", "Study 03", "Study 04", "Study 05", "Study 06", "Study 07", "Study 08", "Study 09", "Study 10", "Study 11", "Study 12"]) # stored level order
df = df.dropna(subset=["study", "effect", "se"]) # listwise deletion over the analysis columns
df["study"] = df["study"].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, ["study", "effect", "se"]) # infinite values stop the run (registry/errors.yaml)
# %% Studies
design = "generic" # inferred from the bound columns
measure = "GEN"
cols = {
"effect": df["effect"].to_numpy(dtype=float),
"se": df["se"].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["study"].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,
},
})
Knapp–Hartung
ReadA Wald z interval treats as if it were known. With few studies, it is not, and the interval runs too narrow.
The Knapp–HartungKnapp–Hartung adjustmentInference for the pooled effect or moderators using a t distribution and a variance rescaled by the observed heterogeneity. adjustment rescales the standard error and uses a t distribution on df. On the guide's data with the Never shrink safeguard on, the p-value moves from p = .121 to p = .149.
Choose it under Inference before you look at the result, especially when is small.
What would you report?
ReflectPassive-smoking studies give I² = 0%, but its interval reaches 55%.
Write one sentence reporting this heterogeneity honestly to a reader who only knows "I² = 0 means they all agree." Then compare it with this: "The estimated between-study variance was zero, though the data are compatible with moderate variation."
Check your understanding
CheckpointCheck yourself
Five small studies give Q with p = 0.40. What can you conclude?
Show the answer
Answer: b
A non-significant Q is compatible with no heterogeneity and also with substantial heterogeneity. Choose the model from the science, not from this test.
Check yourself
A meta-analysis has on 12 df. Using , what is I² as a percentage?
Show the answer
Answer: 75
, or 75%.
Check yourself
Why does Knapp–Hartung usually widen the interval when there are few studies?
Show the answer
Answer: a
The Wald z interval treats the estimated τ² as if known. Knapp–Hartung adjusts the standard error and uses t on df.
Do it in CodeSplash
In the appIn the Meta-analysis studio, the Heterogeneity step puts Q, I² with its interval, τ and the prediction interval side by side. Try the same studies with Inference set to Wald z and then Knapp–Hartung t.
Recap
Recap- Q tests for any heterogeneity, and has low power with few studies.
- I² is a share of variation, not a size; τ and the prediction interval give the size.
- Use Knapp–Hartung when is small, and decide before you see the result.
Concepts in this lesson