Explaining why studies differ
Use a study-level moderator to explain heterogeneity, read QM, QE and R², and guard against false positives and the ecological fallacy.
What runs in CodeSplash
- STAT280Knapp–Hartung meta regression tests Runs in CodeSplash
- Meta-regression (moderators of study effects) Verified in Python and R
You will be able to
- Fit and read a meta-regression on a study-level moderator
- Separate explained heterogeneity (QM, R²) from what remains (QE, τ²)
- Say why moderator findings are observational, even when every study was randomized
Read first
Why would a vaccine vary by latitude?
ReadBCG trials nearer the equator tended to find less protection. One proposed reason is more exposure to environmental mycobacteria there.
A meta-regressionMeta-regressionRegressing study effects on study-level characteristics to explain heterogeneity. tests this by regressing each trial's log risk ratio on a study-level characteristic. It is weighted regression with one extra feature: a for the variation that the moderator does not explain.
How much will latitude explain?
PredictPredict first
Without any moderator, τ² was 0.313.
Guess what share of this between-study variance absolute latitude explains.
Make your guess between 0 and 100 % of τ² explained, then reveal.
Reveal
R² = 76%. Residual τ² falls to 0.076.
That is a lot for one variable, but it is estimated from only 13 trials.
Read the card
ReadQM(1) = 12.59, p = .005; QE(11) = 30.73, p = .001
- QM (moderators)
- 12.591
- p (moderators)
- .005
- QE (residual)
- 30.733
- Residual τ²
- 0.0763
- R² (%)
- 75.627
Plots
View data
| study | weight | ablat | log risk ratio |
|---|---|---|---|
| Aronson 1948 | 2.488 | 44 | −0.8893 |
| Ferguson & Simes 1949 | 3.691 | 55 | −1.585 |
| Rosenthal et al 1960 | 2.034 | 42 | −1.348 |
| Hart & Sutherland 1977 | 10.378 | 52 | −1.442 |
| Frimodt-Moller et al 1973 | 7.840 | 13 | −0.2175 |
| Stein & Aronson 1953 | 12.011 | 44 | −0.7861 |
| Vandiviere et al 1973 | 3.340 | 19 | −1.621 |
| TPT Madras 1980 | 12.452 | 13 | 0.0120 |
| Coetzee & Berjak 1968 | 7.531 | 27 | −0.4694 |
| Rosenthal et al 1961 | 6.695 | 42 | −1.371 |
| Comstock et al 1974 | 11.266 | 18 | −0.3394 |
| Comstock & Webster 1969 | 1.642 | 33 | 0.4459 |
| Comstock et al 1976 | 6.768 | 33 | −0.0173 |
Assumptions
- Enough studies per moderator — 13 studies for 1 moderator term(s).
- Study-level inference — Associations across studies need not hold within them (ecological fallacy).
Coefficients (log risk ratio scale, 95% CI)
| Term | Estimate | SE | t | p | CI low | CI high | p (permutation) |
|---|---|---|---|---|---|---|---|
| intercept | 0.2515 | 0.2839 | 0.8857 | 0.3947 | −0.3734 | 0.8764 | — |
| ablat | −0.0291 | 0.0082 | −3.548 | 0.0046 | −0.0472 | −0.0111 | — |
- Coefficients are on the analysis scale; for ratio measures exp(b) is the multiplicative change per unit of the moderator.
The exact R script · R R version 4.5.1 (2025-06-13)
# Meta-regression (moderators of study effects)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.regression 1.0.1 · spec 1fbc7cc3b5a17fb4
# 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", "ablat")))
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", "ablat")]), , 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", "ablat")) # 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
# %% Design matrix (categories: indicator per level against the first, stored level order)
mods <- c("ablat")
xs <- list(rep(1, nrow(df))); terms <- "intercept"
for (m in mods) {
s <- df[[m]]
if (is.factor(s)) {
for (lv in levels(s)[-1]) { xs[[length(xs) + 1]] <- as.numeric(s == lv); terms <- c(terms, sprintf("%s[%s]", m, lv)) }
} else {
xs[[length(xs) + 1]] <- as.numeric(s); terms <- c(terms, m)
}
}
X <- do.call(cbind, xs)[idx, , drop = FALSE]
if (k < ncol(X) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = "Meta-regression", min = ncol(X) + 1, n = k) # more studies than coefficients
if (all(y == y[1])) {
# Identical effects leave nothing for the moderators to explain (R² and the Knapp–Hartung scale are 0/0).
cs_error("CS_E_CONSTANT", column = "The study effect size")
}
# %% Fit
conf <- 0.95
model <- "random"
fit_method <- if (model == "fixed") "FE" else "REML"
fit <- cs_meta_rma(y, v, X, method = fit_method, test = "knha", knha_trunc = FALSE, level = conf)
null <- cs_meta_rma(y, v, method = fit_method)
tau2_null <- null$tau2
r2 <- if (tau2_null > 0) max(0, (tau2_null - fit$tau2) / tau2_null * 100) else NaN
perm <- list(qm_p = NaN, beta_p = rep(NaN, length(terms)))
model_label <- paste0(if (model == "fixed") "fixed-effects meta-regression" else paste0("mixed-effects, τ² by ", fit_method), if (fit$test == "knha") ", Knapp–Hartung" else "")
stat_name <- if (fit$test == "knha") "t" else "z"
# %% Assumptions
few <- k < 10 * (length(terms) - 1)
assumptions <- list(
list(key = "k_per_moderator", label = "Enough studies per moderator", status = if (few) "warn" else "pass",
detail = paste0(sprintf("%d studies for %d moderator term(s)", k, length(terms) - 1), if (few) "; coefficients may be unstable — prefer the permutation test." else ".")),
list(key = "ecological", label = "Study-level inference", status = "info", detail = "Associations across studies need not hold within them (ecological fallacy).")
)
# %% Result
coef_rows <- lapply(seq_along(terms), function(j) list(term = terms[j], b = fit$beta[j], se = fit$se[j], stat = fit$stat[j], p = fit$pval[j],
low = fit$ci_low[j], high = fit$ci_high[j], perm_p = if (is.nan(perm$beta_p[j])) NULL else perm$beta_p[j]))
values <- list(k = k, n_coef = length(terms), qm = fit$qm, qm_df = fit$qm_df, qm_p = fit$qm_p, qe = fit$qe, qe_df = fit$qe_df, qe_p = fit$qe_p,
tau2 = fit$tau2, tau2_null = tau2_null, r2 = r2, i2 = fit$i2, perm_qm_p = perm$qm_p, measure = measure, measure_label = MEASURE_LABEL,
model_label = model_label)
for (j in seq_along(terms)) {
t <- terms[j]
values[[sprintf("b[%s]", t)]] <- fit$beta[j]; values[[sprintf("se[%s]", t)]] <- fit$se[j]; values[[sprintf("p[%s]", t)]] <- fit$pval[j]
values[[sprintf("ci_low[%s]", t)]] <- fit$ci_low[j]; values[[sprintf("ci_high[%s]", t)]] <- fit$ci_high[j]; values[[sprintf("perm_p[%s]", t)]] <- perm$beta_p[j]
}
charts <- list()
if (length(terms) == 2 && terms[2] == mods[1]) {
vb <- fit$vb
charts[[1]] <- cs_chart("bubble", "metareg-bubble", sprintf("%s against %s", MEASURE_LABEL, mods[1]),
list(x = cs_col(mods[1], X[, 2]), y = cs_col(MEASURE_LABEL, y), weight = cs_col("weight", 1 / (v + fit$tau2)), label = cs_col("study", labels)),
controls = list(intercept = fit$beta[1], slope = fit$beta[2], v00 = vb[1, 1], v01 = vb[1, 2], v11 = vb[2, 2], crit = fit$crit))
}
cs_publish(list(
method = "meta.regression",
methodVersion = "1.0.1",
title = sprintf("Meta-regression on %s (%s)", paste(mods, collapse = ", "), model_label),
engine = cs_engine_info("stats", "nanoparquet"),
n = k,
summary = sprintf("QM = %.3f on %d df, %s; residual QE(%d) = %.2f, %s; τ² %s → %s.", fit$qm, as.integer(fit$qm_df), cs_fmt_p(fit$qm_p), as.integer(fit$qe_df),
fit$qe, cs_fmt_p(fit$qe_p), format(signif(tau2_null, 4)), format(signif(fit$tau2, 4))),
apa = sprintf("QM(%d) = %s, %s; QE(%d) = %s, %s", as.integer(fit$qm_df), cs_fmt_num(fit$qm), cs_fmt_p(fit$qm_p), as.integer(fit$qe_df), cs_fmt_num(fit$qe), cs_fmt_p(fit$qe_p)),
statistics = list(list(key = "qm", label = "QM (moderators)", value = fit$qm), list(key = "qm_p", label = "p (moderators)", value = fit$qm_p, format = "p"),
list(key = "qe", label = "QE (residual)", value = fit$qe), list(key = "tau2", label = "Residual τ²", value = fit$tau2),
list(key = "r2", label = "R² (%)", value = r2)),
tables = list(list(key = "coefficients", title = sprintf("Coefficients (%s scale, %.0f%% CI)", MEASURE_LABEL, conf * 100),
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "b", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "stat", label = stat_name, type = "number"),
list(key = "p", label = "p", type = "number"), list(key = "low", label = "CI low", type = "number"),
list(key = "high", label = "CI high", type = "number"), list(key = "perm_p", label = "p (permutation)", type = "number")),
rows = coef_rows)),
assumptions = assumptions,
warnings = warnings,
notes = if (RATIO) list("Coefficients are on the analysis scale; for ratio measures exp(b) is the multiplicative change per unit of the moderator.") else list(),
charts = charts,
values = values
))
QM(1) = 12.59, p = .005; QE(11) = 30.73, p = .001
- QM (moderators)
- 12.591
- p (moderators)
- .005
- QE (residual)
- 30.733
- Residual τ²
- 0.0763
- R² (%)
- 75.627
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough studies per moderator — 13 studies for 1 moderator term(s).
- Study-level inference — Associations across studies need not hold within them (ecological fallacy).
Coefficients (log risk ratio scale, 95% CI)
| Term | Estimate | SE | t | p | CI low | CI high | p (permutation) |
|---|---|---|---|---|---|---|---|
| intercept | 0.2515 | 0.2839 | 0.8857 | 0.3947 | −0.3734 | 0.8764 | — |
| ablat | −0.0291 | 0.0082 | −3.548 | 0.0046 | −0.0472 | −0.0111 | — |
- Coefficients are on the analysis scale; for ratio measures exp(b) is the multiplicative change per unit of the moderator.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Meta-regression (moderators of study effects)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.regression 1.0.1 · spec 1fbc7cc3b5a17fb4
# 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
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", "ablat"])
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", "ablat"]) # 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", "ablat"]) # 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)
# %% Design matrix (categories: indicator per level against the first, stored level order)
mods = ["ablat"]
cols_x, terms = [np.ones(len(df))], ["intercept"]
for m in mods:
s = df[m]
if isinstance(s.dtype, pd.CategoricalDtype):
for lv in list(s.cat.categories)[1:]:
cols_x.append((s == lv).to_numpy(dtype=float))
terms.append(f"{m}[{lv}]")
else:
cols_x.append(s.to_numpy(dtype=float))
terms.append(m)
X = np.column_stack(cols_x)[idx]
if k < X.shape[1] + 1:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Meta-regression", min=X.shape[1] + 1, n=k) # more studies than coefficients
if np.all(y == y[0]):
# Identical effects leave nothing for the moderators to explain (R² and the Knapp–Hartung scale are 0/0).
cs.cs_error("CS_E_CONSTANT", column="The study effect size")
# %% Fit
conf = 0.95
model = "random"
fit_method = "FE" if model == "fixed" else "REML"
fit = meta.rma(y, v, X, method=fit_method, test="knha", knha_trunc=False, level=conf)
null = meta.rma(y, v, method=fit_method)
tau2_null = null["tau2"]
r2 = max(0.0, (tau2_null - fit["tau2"]) / tau2_null * 100) if tau2_null > 0 else float("nan")
perm = {"qm_p": float("nan"), "beta_p": np.full(len(terms), np.nan)}
model_label = ("fixed-effects meta-regression" if model == "fixed" else f"mixed-effects, τ² by {fit_method}") + (", Knapp–Hartung" if fit["test"] == "knha" else "")
stat_name = "t" if fit["test"] == "knha" else "z"
# %% Assumptions
assumptions = [
{"key": "k_per_moderator", "label": "Enough studies per moderator", "status": "warn" if k < 10 * (len(terms) - 1) else "pass",
"detail": f"{k} studies for {len(terms) - 1} moderator term(s)" + ("; coefficients may be unstable — prefer the permutation test." if k < 10 * (len(terms) - 1) else ".")},
{"key": "ecological", "label": "Study-level inference", "status": "info", "detail": "Associations across studies need not hold within them (ecological fallacy)."},
]
# %% Result
coef_rows = [{"term": terms[j], "b": float(fit["beta"][j]), "se": float(fit["se"][j]), "stat": float(fit["stat"][j]), "p": float(fit["pval"][j]),
"low": float(fit["ci_low"][j]), "high": float(fit["ci_high"][j]), "perm_p": None if math.isnan(perm["beta_p"][j]) else float(perm["beta_p"][j])}
for j in range(len(terms))]
values = {"k": k, "n_coef": len(terms), "qm": fit["qm"], "qm_df": float(fit["qm_df"]), "qm_p": fit["qm_p"], "qe": fit["qe"], "qe_df": float(fit["qe_df"]),
"qe_p": fit["qe_p"], "tau2": fit["tau2"], "tau2_null": tau2_null, "r2": r2, "i2": fit["i2"], "perm_qm_p": float(perm["qm_p"]),
"measure": measure, "measure_label": MEASURE_LABEL, "model_label": model_label}
for j, t in enumerate(terms):
values[f"b[{t}]"] = float(fit["beta"][j]); values[f"se[{t}]"] = float(fit["se"][j]); values[f"p[{t}]"] = float(fit["pval"][j])
values[f"ci_low[{t}]"] = float(fit["ci_low"][j]); values[f"ci_high[{t}]"] = float(fit["ci_high"][j]); values[f"perm_p[{t}]"] = float(perm["beta_p"][j])
charts = []
if len(terms) == 2 and terms[1] == mods[0]:
vb = fit["vb"]
charts.append(cs.chart("bubble", "metareg-bubble", f"{MEASURE_LABEL} against {mods[0]}",
{"x": cs.col(mods[0], [float(t) for t in X[:, 1]]), "y": cs.col(MEASURE_LABEL, [float(t) for t in y]),
"weight": cs.col("weight", [float(t) for t in 1 / (v + fit["tau2"])]), "label": cs.col("study", labels)},
controls={"intercept": float(fit["beta"][0]), "slope": float(fit["beta"][1]), "v00": float(vb[0, 0]), "v01": float(vb[0, 1]),
"v11": float(vb[1, 1]), "crit": float(fit["crit"])}))
cs.publish({
"method": "meta.regression",
"methodVersion": "1.0.1",
"title": f"Meta-regression on {', '.join(mods)} ({model_label})",
"engine": cs.engine_info("numpy", "scipy"),
"n": k,
"summary": f"QM = {fit['qm']:.3f} on {fit['qm_df']} df, {cs.fmt_p(fit['qm_p'])}; residual QE({fit['qe_df']}) = {fit['qe']:.2f}, {cs.fmt_p(fit['qe_p'])}; τ² {tau2_null:.4g} → {fit['tau2']:.4g}.",
"apa": f"QM({fit['qm_df']}) = {cs.fmt_num(fit['qm'])}, {cs.fmt_p(fit['qm_p'])}; QE({fit['qe_df']}) = {cs.fmt_num(fit['qe'])}, {cs.fmt_p(fit['qe_p'])}",
"statistics": [{"key": "qm", "label": "QM (moderators)", "value": fit["qm"]}, {"key": "qm_p", "label": "p (moderators)", "value": fit["qm_p"], "format": "p"},
{"key": "qe", "label": "QE (residual)", "value": fit["qe"]}, {"key": "tau2", "label": "Residual τ²", "value": fit["tau2"]},
{"key": "r2", "label": "R² (%)", "value": r2}],
"tables": [{"key": "coefficients", "title": f"Coefficients ({MEASURE_LABEL} scale, {conf:.0%} CI)",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "b", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "stat", "label": stat_name, "type": "number"},
{"key": "p", "label": "p", "type": "number"}, {"key": "low", "label": "CI low", "type": "number"},
{"key": "high", "label": "CI high", "type": "number"}, {"key": "perm_p", "label": "p (permutation)", "type": "number"}],
"rows": coef_rows}],
"assumptions": assumptions,
"warnings": warnings,
"notes": ["Coefficients are on the analysis scale; for ratio measures exp(b) is the multiplicative change per unit of the moderator."] if RATIO else [],
"charts": charts,
"values": values,
})
- QM tests the moderators: p = .005. Latitude is associated with the effect.
- QE tests what remains: Q = 30.7, p = .001. Latitude does not explain everything.
- I² of the residual: 68%.
The slope is negative: on the log risk ratio scale, the effect gets stronger as latitude rises.
Guarding against chance
ReadWith few studies and many candidate moderators, a moderator can look important by chance. Two safeguards help:
- Knapp–Hartung inference, as here.
- A permutation test, which reshuffles the moderator across studies.
In the teacher-expectancy data, weeks of prior contact has a Wald p = .008 and a permutation p = .013. The permutation p-value is less extreme, as often happens.
QM(1) = 7.13, p = .008; QE(17) = 27.67, p = .049
- QM (moderators)
- 7.127
- p (moderators)
- .008
- QE (residual)
- 27.673
- Residual τ²
- 0.0169
- R² (%)
- 34.950
Plots
View data
| study | weight | weeks | effect |
|---|---|---|---|
| Rosenthal et al. 1974 | 30.816 | 2 | 0.0300 |
| Conn et al. 1968 | 26.007 | 21 | 0.1200 |
| Jose & Cody 1971 | 22.346 | 19 | −0.1400 |
| Pellegrini & Hicks 1972 | 6.412 | 0 | 1.180 |
| Pellegrini & Hicks 1972 1 | 6.534 | 0 | 0.2600 |
| Evans & Rosenthal 1969 | 36.429 | 3 | −0.0600 |
| Fielder et al. 1971 | 36.429 | 17 | −0.0200 |
| Claiborn 1969 | 15.326 | 24 | −0.3200 |
| Kester 1969 | 22.857 | 0 | 0.2700 |
| Maxwell 1970 | 12.523 | 1 | 0.8000 |
| Carter 1970 | 9.255 | 0 | 0.5400 |
| Flowers 1966 | 15.026 | 0 | 0.1800 |
| Keshock 1970 | 9.965 | 1 | −0.0200 |
| Henrikson 1970 | 9.906 | 2 | 0.2300 |
| Fine 1972 | 23.725 | 17 | −0.1800 |
| Grieger 1970 | 22.346 | 5 | −0.0600 |
| Rosenthal & Jacobson 1968 | 27.662 | 1 | 0.3000 |
| Fleming & Anttonen 1971 | 38.986 | 2 | 0.0700 |
| Ginsburg 1970 | 21.209 | 7 | −0.0700 |
Assumptions
- Enough studies per moderator — 19 studies for 1 moderator term(s).
- Study-level inference — Associations across studies need not hold within them (ecological fallacy).
Coefficients (effect scale, 95% CI)
| Term | Estimate | SE | z | p | CI low | CI high | p (permutation) |
|---|---|---|---|---|---|---|---|
| intercept | 0.2054 | 0.0684 | 3.003 | 0.0027 | 0.0713 | 0.3394 | 0.0033 |
| weeks | −0.0165 | 0.0062 | −2.670 | 0.0076 | −0.0287 | −0.0044 | 0.0133 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Meta-regression (moderators of study effects)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.regression 1.0.1 · spec 878ce63bbe8810c7
# Dataset: m1_raudenbush (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_raudenbush.parquet", col_select = c("study", "effect", "se", "weeks")))
n_input <- nrow(df)
df[["study"]] <- factor(df[["study"]], levels = c("Rosenthal et al. 1974", "Conn et al. 1968", "Jose & Cody 1971", "Pellegrini & Hicks 1972", "Pellegrini & Hicks 1972 1", "Evans & Rosenthal 1969", "Fielder et al. 1971", "Claiborn 1969", "Kester 1969", "Maxwell 1970", "Carter 1970", "Flowers 1966", "Keshock 1970", "Henrikson 1970", "Fine 1972", "Grieger 1970", "Rosenthal & Jacobson 1968", "Fleming & Anttonen 1971", "Ginsburg 1970")) # stored level order
df <- df[stats::complete.cases(df[c("study", "effect", "se", "weeks")]), , 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", "weeks")) # 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
# %% Design matrix (categories: indicator per level against the first, stored level order)
mods <- c("weeks")
xs <- list(rep(1, nrow(df))); terms <- "intercept"
for (m in mods) {
s <- df[[m]]
if (is.factor(s)) {
for (lv in levels(s)[-1]) { xs[[length(xs) + 1]] <- as.numeric(s == lv); terms <- c(terms, sprintf("%s[%s]", m, lv)) }
} else {
xs[[length(xs) + 1]] <- as.numeric(s); terms <- c(terms, m)
}
}
X <- do.call(cbind, xs)[idx, , drop = FALSE]
if (k < ncol(X) + 1) cs_error("CS_E_TOO_FEW_ROWS", what = "Meta-regression", min = ncol(X) + 1, n = k) # more studies than coefficients
if (all(y == y[1])) {
# Identical effects leave nothing for the moderators to explain (R² and the Knapp–Hartung scale are 0/0).
cs_error("CS_E_CONSTANT", column = "effect")
}
# %% Fit
conf <- 0.95
model <- "random"
fit_method <- if (model == "fixed") "FE" else "DL"
fit <- cs_meta_rma(y, v, X, method = fit_method, test = "z", knha_trunc = FALSE, level = conf)
null <- cs_meta_rma(y, v, method = fit_method)
tau2_null <- null$tau2
r2 <- if (tau2_null > 0) max(0, (tau2_null - fit$tau2) / tau2_null * 100) else NaN
perm <- cs_meta_permutation(y, v, X, method = fit_method, test = "z", b = 300, seed = 42)
model_label <- paste0(if (model == "fixed") "fixed-effects meta-regression" else paste0("mixed-effects, τ² by ", fit_method), if (fit$test == "knha") ", Knapp–Hartung" else "")
stat_name <- if (fit$test == "knha") "t" else "z"
# %% Assumptions
few <- k < 10 * (length(terms) - 1)
assumptions <- list(
list(key = "k_per_moderator", label = "Enough studies per moderator", status = if (few) "warn" else "pass",
detail = paste0(sprintf("%d studies for %d moderator term(s)", k, length(terms) - 1), if (few) "; coefficients may be unstable — prefer the permutation test." else ".")),
list(key = "ecological", label = "Study-level inference", status = "info", detail = "Associations across studies need not hold within them (ecological fallacy).")
)
# %% Result
coef_rows <- lapply(seq_along(terms), function(j) list(term = terms[j], b = fit$beta[j], se = fit$se[j], stat = fit$stat[j], p = fit$pval[j],
low = fit$ci_low[j], high = fit$ci_high[j], perm_p = if (is.nan(perm$beta_p[j])) NULL else perm$beta_p[j]))
values <- list(k = k, n_coef = length(terms), qm = fit$qm, qm_df = fit$qm_df, qm_p = fit$qm_p, qe = fit$qe, qe_df = fit$qe_df, qe_p = fit$qe_p,
tau2 = fit$tau2, tau2_null = tau2_null, r2 = r2, i2 = fit$i2, perm_qm_p = perm$qm_p, measure = measure, measure_label = MEASURE_LABEL,
model_label = model_label)
for (j in seq_along(terms)) {
t <- terms[j]
values[[sprintf("b[%s]", t)]] <- fit$beta[j]; values[[sprintf("se[%s]", t)]] <- fit$se[j]; values[[sprintf("p[%s]", t)]] <- fit$pval[j]
values[[sprintf("ci_low[%s]", t)]] <- fit$ci_low[j]; values[[sprintf("ci_high[%s]", t)]] <- fit$ci_high[j]; values[[sprintf("perm_p[%s]", t)]] <- perm$beta_p[j]
}
charts <- list()
if (length(terms) == 2 && terms[2] == mods[1]) {
vb <- fit$vb
charts[[1]] <- cs_chart("bubble", "metareg-bubble", sprintf("%s against %s", MEASURE_LABEL, mods[1]),
list(x = cs_col(mods[1], X[, 2]), y = cs_col(MEASURE_LABEL, y), weight = cs_col("weight", 1 / (v + fit$tau2)), label = cs_col("study", labels)),
controls = list(intercept = fit$beta[1], slope = fit$beta[2], v00 = vb[1, 1], v01 = vb[1, 2], v11 = vb[2, 2], crit = fit$crit))
}
cs_publish(list(
method = "meta.regression",
methodVersion = "1.0.1",
title = sprintf("Meta-regression on %s (%s)", paste(mods, collapse = ", "), model_label),
engine = cs_engine_info("stats", "nanoparquet"),
n = k,
summary = sprintf("QM = %.3f on %d df, %s; residual QE(%d) = %.2f, %s; τ² %s → %s.", fit$qm, as.integer(fit$qm_df), cs_fmt_p(fit$qm_p), as.integer(fit$qe_df),
fit$qe, cs_fmt_p(fit$qe_p), format(signif(tau2_null, 4)), format(signif(fit$tau2, 4))),
apa = sprintf("QM(%d) = %s, %s; QE(%d) = %s, %s", as.integer(fit$qm_df), cs_fmt_num(fit$qm), cs_fmt_p(fit$qm_p), as.integer(fit$qe_df), cs_fmt_num(fit$qe), cs_fmt_p(fit$qe_p)),
statistics = list(list(key = "qm", label = "QM (moderators)", value = fit$qm), list(key = "qm_p", label = "p (moderators)", value = fit$qm_p, format = "p"),
list(key = "qe", label = "QE (residual)", value = fit$qe), list(key = "tau2", label = "Residual τ²", value = fit$tau2),
list(key = "r2", label = "R² (%)", value = r2)),
tables = list(list(key = "coefficients", title = sprintf("Coefficients (%s scale, %.0f%% CI)", MEASURE_LABEL, conf * 100),
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "b", label = "Estimate", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "stat", label = stat_name, type = "number"),
list(key = "p", label = "p", type = "number"), list(key = "low", label = "CI low", type = "number"),
list(key = "high", label = "CI high", type = "number"), list(key = "perm_p", label = "p (permutation)", type = "number")),
rows = coef_rows)),
assumptions = assumptions,
warnings = warnings,
notes = if (RATIO) list("Coefficients are on the analysis scale; for ratio measures exp(b) is the multiplicative change per unit of the moderator.") else list(),
charts = charts,
values = values
))
QM(1) = 7.13, p = .008; QE(17) = 27.67, p = .049
- QM (moderators)
- 7.127
- p (moderators)
- .008
- QE (residual)
- 27.673
- Residual τ²
- 0.0169
- R² (%)
- 34.950
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough studies per moderator — 19 studies for 1 moderator term(s).
- Study-level inference — Associations across studies need not hold within them (ecological fallacy).
Coefficients (effect scale, 95% CI)
| Term | Estimate | SE | z | p | CI low | CI high | p (permutation) |
|---|---|---|---|---|---|---|---|
| intercept | 0.2054 | 0.0684 | 3.003 | 0.0027 | 0.0713 | 0.3394 | 0.0033 |
| weeks | −0.0165 | 0.0062 | −2.670 | 0.0076 | −0.0287 | −0.0044 | 0.0133 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Meta-regression (moderators of study effects)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.regression 1.0.1 · spec 878ce63bbe8810c7
# Dataset: m1_raudenbush (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
import codesplash as cs
from codesplash.stats import meta # twins of codesplashr::cs_meta_*
# %% Data
df = pd.read_parquet("tests/parity/fixtures/m1_raudenbush.parquet", columns=["study", "effect", "se", "weeks"])
n_input = len(df)
df["study"] = pd.Categorical(df["study"], categories=["Rosenthal et al. 1974", "Conn et al. 1968", "Jose & Cody 1971", "Pellegrini & Hicks 1972", "Pellegrini & Hicks 1972 1", "Evans & Rosenthal 1969", "Fielder et al. 1971", "Claiborn 1969", "Kester 1969", "Maxwell 1970", "Carter 1970", "Flowers 1966", "Keshock 1970", "Henrikson 1970", "Fine 1972", "Grieger 1970", "Rosenthal & Jacobson 1968", "Fleming & Anttonen 1971", "Ginsburg 1970"]) # stored level order
df = df.dropna(subset=["study", "effect", "se", "weeks"]) # 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", "weeks"]) # 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)
# %% Design matrix (categories: indicator per level against the first, stored level order)
mods = ["weeks"]
cols_x, terms = [np.ones(len(df))], ["intercept"]
for m in mods:
s = df[m]
if isinstance(s.dtype, pd.CategoricalDtype):
for lv in list(s.cat.categories)[1:]:
cols_x.append((s == lv).to_numpy(dtype=float))
terms.append(f"{m}[{lv}]")
else:
cols_x.append(s.to_numpy(dtype=float))
terms.append(m)
X = np.column_stack(cols_x)[idx]
if k < X.shape[1] + 1:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Meta-regression", min=X.shape[1] + 1, n=k) # more studies than coefficients
if np.all(y == y[0]):
# Identical effects leave nothing for the moderators to explain (R² and the Knapp–Hartung scale are 0/0).
cs.cs_error("CS_E_CONSTANT", column="effect")
# %% Fit
conf = 0.95
model = "random"
fit_method = "FE" if model == "fixed" else "DL"
fit = meta.rma(y, v, X, method=fit_method, test="z", knha_trunc=False, level=conf)
null = meta.rma(y, v, method=fit_method)
tau2_null = null["tau2"]
r2 = max(0.0, (tau2_null - fit["tau2"]) / tau2_null * 100) if tau2_null > 0 else float("nan")
perm = meta.permutation_test(y, v, X, method=fit_method, test="z", b=300, seed=42)
model_label = ("fixed-effects meta-regression" if model == "fixed" else f"mixed-effects, τ² by {fit_method}") + (", Knapp–Hartung" if fit["test"] == "knha" else "")
stat_name = "t" if fit["test"] == "knha" else "z"
# %% Assumptions
assumptions = [
{"key": "k_per_moderator", "label": "Enough studies per moderator", "status": "warn" if k < 10 * (len(terms) - 1) else "pass",
"detail": f"{k} studies for {len(terms) - 1} moderator term(s)" + ("; coefficients may be unstable — prefer the permutation test." if k < 10 * (len(terms) - 1) else ".")},
{"key": "ecological", "label": "Study-level inference", "status": "info", "detail": "Associations across studies need not hold within them (ecological fallacy)."},
]
# %% Result
coef_rows = [{"term": terms[j], "b": float(fit["beta"][j]), "se": float(fit["se"][j]), "stat": float(fit["stat"][j]), "p": float(fit["pval"][j]),
"low": float(fit["ci_low"][j]), "high": float(fit["ci_high"][j]), "perm_p": None if math.isnan(perm["beta_p"][j]) else float(perm["beta_p"][j])}
for j in range(len(terms))]
values = {"k": k, "n_coef": len(terms), "qm": fit["qm"], "qm_df": float(fit["qm_df"]), "qm_p": fit["qm_p"], "qe": fit["qe"], "qe_df": float(fit["qe_df"]),
"qe_p": fit["qe_p"], "tau2": fit["tau2"], "tau2_null": tau2_null, "r2": r2, "i2": fit["i2"], "perm_qm_p": float(perm["qm_p"]),
"measure": measure, "measure_label": MEASURE_LABEL, "model_label": model_label}
for j, t in enumerate(terms):
values[f"b[{t}]"] = float(fit["beta"][j]); values[f"se[{t}]"] = float(fit["se"][j]); values[f"p[{t}]"] = float(fit["pval"][j])
values[f"ci_low[{t}]"] = float(fit["ci_low"][j]); values[f"ci_high[{t}]"] = float(fit["ci_high"][j]); values[f"perm_p[{t}]"] = float(perm["beta_p"][j])
charts = []
if len(terms) == 2 and terms[1] == mods[0]:
vb = fit["vb"]
charts.append(cs.chart("bubble", "metareg-bubble", f"{MEASURE_LABEL} against {mods[0]}",
{"x": cs.col(mods[0], [float(t) for t in X[:, 1]]), "y": cs.col(MEASURE_LABEL, [float(t) for t in y]),
"weight": cs.col("weight", [float(t) for t in 1 / (v + fit["tau2"])]), "label": cs.col("study", labels)},
controls={"intercept": float(fit["beta"][0]), "slope": float(fit["beta"][1]), "v00": float(vb[0, 0]), "v01": float(vb[0, 1]),
"v11": float(vb[1, 1]), "crit": float(fit["crit"])}))
cs.publish({
"method": "meta.regression",
"methodVersion": "1.0.1",
"title": f"Meta-regression on {', '.join(mods)} ({model_label})",
"engine": cs.engine_info("numpy", "scipy"),
"n": k,
"summary": f"QM = {fit['qm']:.3f} on {fit['qm_df']} df, {cs.fmt_p(fit['qm_p'])}; residual QE({fit['qe_df']}) = {fit['qe']:.2f}, {cs.fmt_p(fit['qe_p'])}; τ² {tau2_null:.4g} → {fit['tau2']:.4g}.",
"apa": f"QM({fit['qm_df']}) = {cs.fmt_num(fit['qm'])}, {cs.fmt_p(fit['qm_p'])}; QE({fit['qe_df']}) = {cs.fmt_num(fit['qe'])}, {cs.fmt_p(fit['qe_p'])}",
"statistics": [{"key": "qm", "label": "QM (moderators)", "value": fit["qm"]}, {"key": "qm_p", "label": "p (moderators)", "value": fit["qm_p"], "format": "p"},
{"key": "qe", "label": "QE (residual)", "value": fit["qe"]}, {"key": "tau2", "label": "Residual τ²", "value": fit["tau2"]},
{"key": "r2", "label": "R² (%)", "value": r2}],
"tables": [{"key": "coefficients", "title": f"Coefficients ({MEASURE_LABEL} scale, {conf:.0%} CI)",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "b", "label": "Estimate", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "stat", "label": stat_name, "type": "number"},
{"key": "p", "label": "p", "type": "number"}, {"key": "low", "label": "CI low", "type": "number"},
{"key": "high", "label": "CI high", "type": "number"}, {"key": "perm_p", "label": "p (permutation)", "type": "number"}],
"rows": coef_rows}],
"assumptions": assumptions,
"warnings": warnings,
"notes": ["Coefficients are on the analysis scale; for ratio measures exp(b) is the multiplicative change per unit of the moderator."] if RATIO else [],
"charts": charts,
"values": values,
})
Is this causal?
ReflectEvery BCG trial was randomized. Does that make the latitude finding causal?
No. Patients were randomized to vaccine or not, but trials were never randomized to latitudes. Latitude travels with year, allocation method and more. A moderator analysis is an observational comparison between studies, an ecologicalEcological fallacyAssuming that a pattern across groups or regions holds for the individuals inside them. one if you apply it to individuals.
Name one other thing that might differ between trials near and far from the equator.
Check your understanding
CheckpointCheck yourself
A meta-regression gives QM with p < 0.01 and QE with p < 0.01. What does this say?
Show the answer
Answer: a
QM tests the moderators and QE tests the residual. Both can be significant, as with latitude in the BCG trials.
Check yourself
τ² falls from 0.40 without moderators to 0.20 with one. What is R², as a percentage?
Show the answer
Answer: 50
, or 50% of the between-study variance.
Check yourself
You have 9 studies and six candidate moderators. Which plan is most defensible?
Show the answer
Answer: c
A common rule of thumb asks for about ten studies per moderator. Pre-specify, and treat the rest as exploratory.
Do it in CodeSplash
In the appIn the Meta-analysis studio, the template Explain why studies differ opens meta-regression and subgroups in the Heterogeneity step. Add a study-level column as a moderator, and turn on Permutation test when studies are few.
Recap
Recap- Meta-regression asks whether study characteristics track study effects.
- QM and R² describe what the moderator explains; QE and τ² describe what is left.
- Between-study comparisons are observational, even for randomized trials.
Concepts in this lesson