Skip to content

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

Applied ~14 min9 steps

What runs in CodeSplash

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

01

Three numbers people mix up

Read

For 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?
02

Same I², different story

Predict

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

Study A varies moreStudy B varies moreYou cannot tell from I² alone
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.

03

Watch Q and I² respond

Explore

Change 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²)?

0.50
How sure?
10
0.30
0.20
12345678910FixedRandom

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.

The anatomy below shows how Q is computed from weighted squared deviations.

BExplorable · Cochran Q heterogeneity test

Do the studies estimate one common effect?

14
0.30
0.25
0.00

Adds bias × SE: small studies report bigger effects.

0.050

Your data

Simulated with a known ρ

If H₀ were true

Q = 12.13
  1. The reference: how Q varies across samples when H₀ is true.
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .517).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

Q=∑iwi(yi−yˉw)2∼χk−12,wi=1/sei2Q = \sum_i w_i(y_i-\bar y_w)^2\sim\chi^2_{k-1},\qquad w_i = 1/\mathrm{se}_i^2

With your numbers

Q=12.13,yˉw=0.35,ν=13Q = 12.13,\quad \bar y_w = 0.35,\quad \nu = 13
yi, seiy_i,\ \mathrm{se}_i
study effects and standard errors
yˉw\bar y_w
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 H0.

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

04

A quiet Q is not agreement

Read

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

Meta-analysis of 12 studies (random effects, τ² by REML)Recorded · Python and R agreeRecorded 2026-11-17 · 30 values compared
R

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

Studies and the pooled estimateHow do the studies' effects compare, and what is the pooled effect and its spread?
View data
effecthighrowstudylowweight %
0.30410.7187studyStudy 01−0.11056.800
−0.01590.3299studyStudy 02−0.36189.773
0.22780.6420studyStudy 03−0.18636.815
0.18310.5134studyStudy 04−0.147310.711
0.06670.3461studyStudy 05−0.212814.968
−0.30320.1610studyStudy 06−0.76755.423
0.05300.5885studyStudy 07−0.48264.075
−0.00400.3384studyStudy 08−0.34649.968
0.22270.7180studyStudy 09−0.27264.763
0.10520.3891studyStudy 10−0.178614.509
0.11840.5787studyStudy 11−0.34205.515
0.05390.4722studyStudy 12−0.36446.679
0.08560.1937summaryPooled (RE)−0.0226100
Funnel plotAre small studies' effects distributed symmetrically around the pooled effect?
View data
effectstudystandard error
0.3041Study 010.2115
−0.0159Study 020.1764
0.2278Study 030.2113
0.1831Study 040.1685
0.0667Study 050.1426
−0.3032Study 060.2369
0.0530Study 070.2732
−0.0040Study 080.1747
0.2227Study 090.2527
0.1052Study 100.1448
0.1184Study 110.2349
0.0539Study 120.2134
Radial (Galbraith) plotWhich studies fall outside what one common effect would predict?
View data
studyprecision (1/SE)standardized estimate
Study 014.7281.438
Study 025.668−0.0903
Study 034.7331.078
Study 045.9331.086
Study 057.0140.4676
Study 064.222−1.280
Study 073.6600.1939
Study 085.724−0.0230
Study 093.9570.8812
Study 106.9060.7268
Study 114.2580.5039
Study 124.6860.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)

StudyEstimateCI lowCI highWeight %
Study 010.3041−0.11050.71876.800
Study 02−0.0159−0.36180.32999.773
Study 030.2278−0.18630.64206.815
Study 040.1831−0.14730.513410.711
Study 050.0667−0.21280.346114.968
Study 06−0.3032−0.76750.16105.423
Study 070.0530−0.48260.58854.075
Study 08−0.0040−0.34640.33849.968
Study 090.2227−0.27260.71804.763
Study 100.1052−0.17860.389114.509
Study 110.1184−0.34200.57875.515
Study 120.0539−0.36440.47226.679

Heterogeneity

EstimateCI lowCI high
τ²000.0211
τ000.1452
I² (%)0036.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
  )
))
Python

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)

StudyEstimateCI lowCI highWeight %
Study 010.3041−0.11050.71876.800
Study 02−0.0159−0.36180.32999.773
Study 030.2278−0.18630.64206.815
Study 040.1831−0.14730.513410.711
Study 050.0667−0.21280.346114.968
Study 06−0.3032−0.76750.16105.423
Study 070.0530−0.48260.58854.075
Study 08−0.0040−0.34640.33849.968
Study 090.2227−0.27260.71804.763
Study 100.1052−0.17860.389114.509
Study 110.1184−0.34200.57875.515
Study 120.0539−0.36440.47226.679

Heterogeneity

EstimateCI lowCI high
τ²000.0211
τ000.1452
I² (%)0036.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,
    },
})
05

Knapp–Hartung

Read

A Wald z interval treats τ^2\hat\tau^2 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 k−1k-1 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 kk is small.

06

What would you report?

Reflect

Passive-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."

07

Check your understanding

Checkpoint

Check 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 Q=48Q = 48 on 12 df. Using I2=(Q−df)/QI^2 = (Q - df)/Q, what is I² as a percentage?

Show the answer

Answer: 75

(48−12)/48=0.75(48 - 12)/48 = 0.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 k−1k-1 df.

08

Do it in CodeSplash

In the app

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

09

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 kk is small, and decide before you see the result.

Concepts in this lesson