BMeta-analysis · meta.regression
Meta-regression (moderators of study effects)
Do study characteristics explain why the studies' effects differ?
Mixed-effects meta-regression of study effect sizes on study-level moderators: coefficients with Wald or Knapp–Hartung tests, the omnibus moderator test (QM), residual heterogeneity (QE, τ², I²), the share of heterogeneity explained (R²) and an optional permutation test that guards against the inflated false positives meta-regressions with few studies are prone to.
A real result
Example “Guide knha”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
QM(1) = 0.29, p = .600; QE(10) = 5.37, p = .865
- QM (moderators)
- 0.2928
- p (moderators)
- .600
- QE (residual)
- 5.373
- Residual τ²
- 0
- R² (%)
- —
Plots
View data
| study | weight | moderator | effect |
|---|---|---|---|
| Study 01 | 22.350 | 1 | 0.3041 |
| Study 02 | 32.123 | 2 | −0.0159 |
| Study 03 | 22.401 | 3 | 0.2278 |
| Study 04 | 35.205 | 4 | 0.1831 |
| Study 05 | 49.198 | 5 | 0.0667 |
| Study 06 | 17.824 | 6 | −0.3032 |
| Study 07 | 13.394 | 7 | 0.0530 |
| Study 08 | 32.764 | 8 | −0.0040 |
| Study 09 | 15.656 | 9 | 0.2227 |
| Study 10 | 47.688 | 10 | 0.1052 |
| Study 11 | 18.127 | 11 | 0.1184 |
| Study 12 | 21.954 | 12 | 0.0539 |
Assumptions
- Enough studies per moderator — 12 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 | t | p | CI low | CI high | p (permutation) |
|---|---|---|---|---|---|---|---|
| intercept | 0.1268 | 0.0863 | 1.470 | 0.1724 | −0.0654 | 0.3190 | — |
| moderator | −0.0065 | 0.0120 | −0.5411 | 0.6003 | −0.0333 | 0.0203 | — |
QM(1) = 0.29, p = .600; QE(10) = 5.37, p = .865
- QM (moderators)
- 0.2928
- p (moderators)
- .600
- QE (residual)
- 5.373
- Residual τ²
- 0
- R² (%)
- —
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough studies per moderator — 12 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 | t | p | CI low | CI high | p (permutation) |
|---|---|---|---|---|---|---|---|
| intercept | 0.1268 | 0.0863 | 1.470 | 0.1724 | −0.0654 | 0.3190 | — |
| moderator | −0.0065 | 0.0120 | −0.5411 | 0.6003 | −0.0333 | 0.0203 | — |
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Guide knham1_guide · effect: effect · moderators: moderator · se: se · study: study
- Bcg latitude knham1_bcg · events_1: events_1 · events_2: events_2 · moderators: ablat · study: trial · total_1: total_1 · total_2: total_2
- Bcg latitude allocationm1_bcg · events_1: events_1 · events_2: events_2 · moderators: ablat, alloc · study: trial · total_1: total_1 · total_2: total_2
- Raudenbush weeks permutationm1_raudenbush · effect: effect · moderators: weeks · se: se · study: study
- Molloy age fixedm1_molloy · moderators: meanage, design · n: n · r: r · study: study
- Degenerate constantm1_guide · effect: effect · moderators: moderator · se: se · study: study
- Degenerate n2m1_guide · effect: effect · moderators: moderator · se: se · study: study
In the guides
Tests from the statistics guide this method runs
What you need
- Study labels (optional)categorical · 0–1 column
- Names the studies in tables and the forest plot.
- Estimate (or ratio)numeric · 0–1 column
- Generic: each study's estimate on an additive scale (log OR, SMD …). With CI limits: the ratio itself (OR, RR, HR).
- Standard errornumeric · 0–1 column
- Generic design: the estimate's standard error.
- Lower CI limit (ratio)numeric · 0–1 column
- Ratio with CI design: the reported lower limit; the SE comes from the CI width on the log scale.
- Upper CI limit (ratio)numeric · 0–1 column
- Ratio with CI design: the reported upper limit.
- Events, group 1numeric · 0–1 column
- Two-arm counts: events in the first (treatment) arm.
- Total, group 1numeric · 0–1 column
- Participants in the first arm (counts and means designs).
- Events, group 2numeric · 0–1 column
- Two-arm counts: events in the second (control) arm.
- Total, group 2numeric · 0–1 column
- Participants in the second arm (counts and means designs).
- Mean, group 1numeric · 0–1 column
- Means design: mean of the first arm.
- SD, group 1numeric · 0–1 column
- Means design: standard deviation of the first arm (not the SE).
- Mean, group 2numeric · 0–1 column
- Means design: mean of the second arm.
- SD, group 2numeric · 0–1 column
- Means design: standard deviation of the second arm.
- Correlationnumeric · 0–1 column
- Correlation design: each study's Pearson r.
- Sample size (correlation)numeric · 0–1 column
- Correlation design: the number of pairs behind each r.
- Moderatorsnumeric / categorical / boolean · 1–5 columns
- Study-level characteristics that may explain heterogeneity (year, dose, design …); categories are compared with the first level.
Choices you make
hypothesis
- Study datadefault auto
What each row reports. Auto picks it from the columns you bound.
- Detect from the columns(default) — Counts → two-arm counts; means → means; r → correlations; CI limits → ratio with CI; else estimate + SE.
- Two-arm counts — Each study gives events and totals in two arms; pick it for yes/no outcomes.
- Means and SDs — Each study gives means, SDs and sizes in two arms; pick it for numeric outcomes.
- Correlations — Each study gives a correlation and its sample size; pick it for associations.
- Ratio with CI — Each study gives a ratio with its CI, worked back to a log-scale SE; pick it for published OR, RR or HR.
- Estimate and SE — Each study gives an estimate and its SE; pick it when effects are already computed.
- Effect measuredefault auto
The scale studies are pooled on (ratios on the log scale and reported back as ratios).
- Default for the data(default) — Odds ratio for counts, Hedges' g for means, Fisher's z for correlations.
- Odds ratio — Odds ratio from two-arm counts; steady across baseline risks, and the usual choice for rare events.
- Risk ratio — Risk ratio from two-arm counts; easier to explain than odds, on a ratio scale.
- Risk difference — Risk difference from two-arm counts; gives the absolute effect, which often varies more across studies.
- Standardized mean difference (Hedges' g) — Mean difference in SD units (Hedges' g); pick it when studies use different scales.
- Mean difference — Raw units; only when every study measured the outcome on the same scale.
- Fisher's z (reported as r) — Transforms correlations by Fisher's z before pooling and reports r; the usual choice for correlations.
- Raw correlation — Pools correlations on their raw scale; easy to read, but each one's variance depends on r.
- Modeldefault random
Random effects keeps between-study variation not explained by the moderators; common effect assumes none.
- Random effects(default) — True effects vary between studies; the pooled value is their mean.
- Common effect (fixed) — One true effect shared by every study; inference applies only to these studies.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- τ² estimatordefault REML
How the between-study variance is estimated; REML and Paule–Mandel are the usual recommendations.
- Restricted maximum likelihood (REML)(default) — Estimates between-study variance by restricted likelihood; the recommended all-rounder.
- Paule–Mandel — Chooses τ² so Cochran's Q matches its expected value; a good alternative to REML, also for binary outcomes.
- DerSimonian–Laird — Classic method-of-moments; underestimates τ² with few studies.
- Maximum likelihood — Uses the full likelihood; needed to compare moderator models, though τ² runs low with few studies.
- Hedges (unweighted moments) — An unweighted moment estimate; easy to compute, but noisy when studies differ in size.
- Sidik–Jonkman — Starts from a rough τ² and refines it once; rarely gives zero, and overestimates when heterogeneity is low.
- Empirical Bayes (Morris) — An empirical Bayes estimate; gives the same answer as Paule–Mandel when there are no moderators.
- Inferencedefault z
Knapp–Hartung (HKSJ) uses a t distribution with an adjusted SE; better coverage with few studies.
- Wald z(default) — Uses the normal distribution; fine with many studies, but intervals run narrow with few.
- Knapp–Hartung t — Uses a t distribution with an adjusted SE; better coverage with few studies.
- Never shrink the Knapp–Hartung SEdefault off
Modified Knapp–Hartung: use max(1, q) so the interval is never narrower than the Wald one.
- Permutation testdefault off
Permute the moderators over studies to get p-values that hold with few studies (Higgins & Thompson 2004).
- Permutationsdefault 1000
Draws on the shared random stream: Python and R agree exactly.
options
- Zero cellsdefault only0
Continuity correction for log OR / RR when a study has a zero cell.
- Add ½ to studies with a zero cell(default) — Adds ½ to the cells of studies with a zero; the usual choice.
- Add ½ to every study — Adds ½ to every study's cells; matches some older software, and pulls small studies towards no effect.
- No correction (drop undefined) — Adds nothing, so studies with an undefined effect drop out; pick it as a sensitivity check.
- Leave out double-zero studiesdefault on
Studies with no events (or only events) in both arms carry no information about OR or RR.
- Reported CI level (ratio design)default 0.95
The level of the confidence intervals the studies reported (usually 95%).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Comparable studiesNot checked from data: state why it holds
Studies estimate the same kind of effect in comparable populations.
Independent estimatesNot checked from data: state why it holds
One estimate per study; several outcomes or arms from one study need a multilevel model.
Enough studies per moderator
About 10 studies per moderator; fewer gives unstable, overfitted coefficients.
Study-level inference
Moderators describe studies, not participants: an association across studies need not hold within them (ecological fallacy).
What it reports
- Tests: Moderators explain between-study differences (QM)
- Tests: Residual heterogeneity (QE)
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n_coef
- How many coefficients the model estimated, counting the intercept.
- qm
- Regressing study effects on study-level characteristics to explain heterogeneity.
- qm_df
- How much independent information is left to estimate variability after fitting the model.
- qm_p
- Regressing study effects on study-level characteristics to explain heterogeneity.
- qe
- The weighted sum of squared deviations of study estimates from the common-effect estimate; χ² with k − 1 df if all studies share one effect.
- qe_df
- How much independent information is left to estimate variability after fitting the model.
- qe_p
- The weighted sum of squared deviations of study estimates from the common-effect estimate; χ² with k − 1 df if all studies share one effect.
- tau2
- How much the studies' true effects vary around their mean; τ is the same on the effect's own scale.
- tau2_null
- How much the studies' true effects vary around their mean; τ is the same on the effect's own scale.
- r2
- Regressing study effects on study-level characteristics to explain heterogeneity.
- i2
- The share of the variation in study estimates that comes from real differences between studies rather than sampling error.
- perm_qm_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- measure
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- measure_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- model_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
Per group, level or term: b[<term>], se[<term>], p[<term>], ci_low[<term>], ci_high[<term>], perm_p[<term>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Mixed-effects fit (Fisher scoring for REML/ML, the same step rule in both engines), Knapp–Hartung and permutation tests (moderator rows permuted on the shared Wichmann–Hill stream) are codesplash twins.
The exact script CodeSplash ran for example “Guide knha” · 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 3f41460108549314
# 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
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", "moderator"])
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", "moderator"]) # 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", "moderator"]) # 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 = ["moderator"]
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 "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,
})
The exact script CodeSplash ran for example “Guide knha” · 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 3f41460108549314
# 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", "moderator")))
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", "moderator")]), , 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", "moderator")) # 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("moderator")
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 "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
))
Sources
- Thompson, S. G., & Higgins, J. P. T. (2002). How should meta-regression analyses be undertaken and interpreted? Statistics in Medicine, 21, 1559–1573.
- Higgins, J. P. T., & Thompson, S. G. (2004). Controlling the risk of spurious findings from meta-regression. Statistics in Medicine, 23, 1663–1682.
- Knapp, G., & Hartung, J. (2003). Improved tests for a random effects meta-regression with a single covariate. Statistics in Medicine, 22, 2693–2710.
- Viechtbauer, W., López-López, J. A., Sánchez-Meca, J., & Marín-Martínez, F. (2015). A comparison of procedures to test for moderators in mixed-effects meta-regression models. Psychological Methods, 20, 360–374.
From the CodeSplash method registry · meta.regression v1.0.1.