Skip to content

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.

Applied ~14 min10 steps

What runs in CodeSplash

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

01

Thirteen trials, one question

Read

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

Two models, one table

Predict

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

Common effect is widerRandom effects is widerThey match
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.

03

Weighted by precision

Read

Each study ii gets an effect yiy_i and a sampling variance viv_i. The pooled estimate is a weighted average:

μ^=∑iwiyi∑iwi,wi=1vi+τ^2\hat\mu = \frac{\sum_i w_i y_i}{\sum_i w_i}, \qquad w_i = \frac{1}{v_i + \hat\tau^2}

In a common-effectCommon-effect modelAssumes every study estimates one shared true effect; differences are sampling error only. model τ^2=0\hat\tau^2 = 0, 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 τ^2\hat\tau^2 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.

04

Change the disagreement

Explore

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

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.

Then try the opposite: set the disagreement to zero. The two models should now agree closely.

05

Read the card

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

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]

Plots

Studies and the pooled estimateHow do the studies' effects compare, and what is the pooled effect and its spread?
View data
risk ratiohighrowstudylowweight %
0.41091.257studyAronson 19480.13435.059
0.20490.4864studyFerguson & Simes 19490.08636.365
0.25970.9186studyRosenthal et al 19600.07344.436
0.23660.3121studyHart & Sutherland 19770.17939.699
0.80451.254studyFrimodt-Moller et al 19730.51638.868
0.45560.5362studyStein & Aronson 19530.387110.096
0.19770.4989studyVandiviere et al 19730.07846.027
1.0121.145studyTPT Madras 19800.894610.189
0.62540.9962studyCoetzee & Berjak 19680.39268.743
0.25380.4310studyRosenthal et al 19610.14948.368
0.71220.8860studyComstock et al 19740.57259.925
1.5626.528studyComstock & Webster 19690.37373.822
0.98281.659studyComstock et al 19760.58218.403
0.48940.6962summaryPooled (RE)0.3441100
Funnel plotAre small studies' effects distributed symmetrically around the pooled effect?
View data
log risk ratiostudystandard error
−0.8893Aronson 19480.5706
−1.585Ferguson & Simes 19490.4411
−1.348Rosenthal et al 19600.6445
−1.442Hart & Sutherland 19770.1415
−0.2175Frimodt-Moller et al 19730.2263
−0.7861Stein & Aronson 19530.0831
−1.621Vandiviere et al 19730.4722
0.0120TPT Madras 19800.0629
−0.4694Coetzee & Berjak 19680.2376
−1.371Rosenthal et al 19610.2702
−0.3394Comstock et al 19740.1114
0.4459Comstock & Webster 19690.7297
−0.0173Comstock et al 19760.2672
Radial (Galbraith) plotWhich studies fall outside what one common effect would predict?
View data
studyprecision (1/SE)standardized estimate
Aronson 19481.753−1.559
Ferguson & Simes 19492.267−3.594
Rosenthal et al 19601.552−2.092
Hart & Sutherland 19777.069−10.191
Frimodt-Moller et al 19734.419−0.9613
Stein & Aronson 195312.034−9.460
Vandiviere et al 19732.118−3.432
TPT Madras 198015.8880.1899
Coetzee & Berjak 19684.209−1.976
Rosenthal et al 19613.701−5.075
Comstock et al 19748.976−3.046
Comstock & Webster 19691.3700.6111
Comstock et al 19763.742−0.0648
L'Abbé plot: event risk in each armDoes the treatment's benefit depend on the baseline risk?
View data
studyrisk, group 1risk, group 2participants
Aronson 19480.03250.0791262
Ferguson & Simes 19490.01960.0957609
Rosenthal et al 19600.01300.0500451
Hart & Sutherland 19770.00460.019326,465
Frimodt-Moller et al 19730.00650.008110,877
Stein & Aronson 19530.11680.25642,992
Vandiviere et al 19730.00310.01593,174
TPT Madras 19800.00570.0056176,782
Coetzee & Berjak 19680.00390.006214,776
Rosenthal et al 19610.00990.03903,381
Comstock et al 19740.00370.005277,972
Comstock & Webster 19690.00200.00134,839
Comstock et al 19760.00160.001634,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)

StudyEstimateCI lowCI highWeight %
Aronson 19480.41090.13431.2575.059
Ferguson & Simes 19490.20490.08630.48646.365
Rosenthal et al 19600.25970.07340.91864.436
Hart & Sutherland 19770.23660.17930.31219.699
Frimodt-Moller et al 19730.80450.51631.2548.868
Stein & Aronson 19530.45560.38710.536210.096
Vandiviere et al 19730.19770.07840.49896.027
TPT Madras 19801.0120.89461.14510.189
Coetzee & Berjak 19680.62540.39260.99628.743
Rosenthal et al 19610.25380.14940.43108.368
Comstock et al 19740.71220.57250.88609.925
Comstock & Webster 19691.5620.37376.5283.822
Comstock et al 19760.98280.58211.6598.403

Heterogeneity

EstimateCI lowCI high
τ²0.31320.11971.111
τ0.55970.34601.054
I² (%)92.22181.92197.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
  )
))
Python

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)

StudyEstimateCI lowCI highWeight %
Aronson 19480.41090.13431.2575.059
Ferguson & Simes 19490.20490.08630.48646.365
Rosenthal et al 19600.25970.07340.91864.436
Hart & Sutherland 19770.23660.17930.31219.699
Frimodt-Moller et al 19730.80450.51631.2548.868
Stein & Aronson 19530.45560.38710.536210.096
Vandiviere et al 19730.19770.07840.49896.027
TPT Madras 19801.0120.89461.14510.189
Coetzee & Berjak 19680.62540.39260.99628.743
Rosenthal et al 19610.25380.14940.43108.368
Comstock et al 19740.71220.57250.88609.925
Comstock & Webster 19691.5620.37376.5283.822
Comstock et al 19760.98280.58211.6598.403

Heterogeneity

EstimateCI lowCI high
τ²0.31320.11971.111
τ0.55970.34601.054
I² (%)92.22181.92197.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.

06

Which interval answers which question?

Reflect

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

07

Check your understanding

Checkpoint

Check yourself

Adding τ^2\hat\tau^2 to each study's variance has what effect on the weights?

Show the answer

Answer: b

Each weight is 1/(vi+τ^2)1/(v_i + \hat\tau^2). A large τ^2\hat\tau^2 swamps the differences in viv_i, so the weights even out, though they stay unequal unless every viv_i 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.

08

Do it in CodeSplash

In the app

Open 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:

09

The calculation in code

In the app

This script pools the log odds ratios with the DerSimonian–Laird τ^2\hat\tau^2. The result matches the bcg-or-dl-knha example's estimate of 0.474.

Python
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)
R
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)
10

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