Skip to content

BMeta-analysis · meta.bias

Small-study effects and publication bias

Do smaller studies report systematically different effects, as publication bias would cause?

Funnel-plot asymmetry and its consequences: Egger's regression test (classic or meta-regression on the standard error), Begg and Mazumdar's rank correlation, Duval and Tweedie's trim-and-fill (L0 or R0), PET-PEESE and Rosenthal's fail-safe N. Asymmetry has several causes besides publication bias (heterogeneity, chance, outcome definitions), and these tests have little power with few studies.

Verified in Python and R Python and R agree to 10 decimals Also called Egger's test, Begg's test, funnel plot asymmetry…

A real result

Example “Guide egger begg”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Small-study effects in 12 studiesRecorded · Python and R agreeRecorded 2026-11-17 · 24 values compared
R

Egger's test p = .962; Begg's τ = −0.03, p = .947; trim-and-fill k₀ = 0

p (Egger)
.962
p (Begg)
.947
Studies imputed
0

Plots

Funnel plot with imputed studiesAre small studies' effects distributed symmetrically around the pooled effect?
View data
effectstudystudystandard error
0.3041observedStudy 010.2115
−0.0159observedStudy 020.1764
0.2278observedStudy 030.2113
0.1831observedStudy 040.1685
0.0667observedStudy 050.1426
−0.3032observedStudy 060.2369
0.0530observedStudy 070.2732
−0.0040observedStudy 080.1747
0.2227observedStudy 090.2527
0.1052observedStudy 100.1448
0.1184observedStudy 110.2349
0.0539observedStudy 120.2134

Assumptions

  • Enough studies — 12 studies.
  • Low heterogeneity — I² = 0.0%.

Small-study diagnostics (effect)

TestStatisticp
Egger (classic)−0.04940.9616limit effect 0.0953 [-0.353, 0.544]
Begg–Mazumdar−0.03030.9466exact Kendall null
Trim-and-fill (L0)0—0 imputed on the right (larger effects); adjusted 0.0856 [-0.0226, 0.194]
PET-PEESE0.09530.6463PET estimate 0.0953 [-0.353, 0.544]
Fail-safe N (Rosenthal)0—robust if above 5k + 10 = 70
  • Asymmetry can come from publication bias, heterogeneity, chance or differences in study quality; these tests cannot tell which.
Python

Egger's test p = .962; Begg's τ = −0.03, p = .947; trim-and-fill k₀ = 0

p (Egger)
.962
p (Begg)
.947
Studies imputed
0

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Enough studies — 12 studies.
  • Low heterogeneity — I² = 0.0%.

Small-study diagnostics (effect)

TestStatisticp
Egger (classic)−0.04940.9616limit effect 0.0953 [-0.353, 0.544]
Begg–Mazumdar−0.03030.9466exact Kendall null
Trim-and-fill (L0)0—0 imputed on the right (larger effects); adjusted 0.0856 [-0.0226, 0.194]
PET-PEESE0.09530.6463PET estimate 0.0953 [-0.353, 0.544]
Fail-safe N (Rosenthal)0—robust if above 5k + 10 = 70
  • Asymmetry can come from publication bias, heterogeneity, chance or differences in study quality; these tests cannot tell which.

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 egger beggm1_guide · effect: effect · se: se · study: study
  • Guide regtestm1_guide · effect: effect · se: se · study: study
  • Bcg rrm1_bcg · events_1: events_1 · events_2: events_2 · study: trial · total_1: total_1 · total_2: total_2
  • Hackshaw ratio r0m1_hackshaw · ci_high: or_high · ci_low: or_low · effect: or · study: study
  • Molloy leftm1_molloy · n: n · r: r · study: study
  • Degenerate constantm1_guide · effect: effect · se: se · study: study
  • Degenerate n2m1_guide · effect: effect · 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.

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.
Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

statistics

Egger testdefault classic

Variant of Egger's test for funnel-plot asymmetry.

  • Classic (standardized effect on precision, t test)(default) — Regresses standardized effects on precision and uses a t test; the original Egger test.
  • Meta-regression on the standard error (z test) — metafor's regtest default; its intercept is the effect expected as SE → 0.
τ² 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.
Trim-and-fill estimatordefault L0

Estimator for the number of missing studies in trim-and-fill. L0 is the usual default.

  • L0 (default)(default) — Estimates the missing-study count from a rank-sum statistic; the usual choice.
  • R0 — Estimates the count from the longest run of ranks on one side; can be less stable in small meta-analyses.
Side of the missing studiesdefault auto

Auto: the side opposite the regression slope of effect on SE.

  • Estimate from the data(default) — Picks the side opposite the regression slope of effect on SE; the usual choice.
  • Left (small effects missing) — Fills in missing studies on the left of the funnel; pick it when small effects are the ones likely left unpublished.
  • Right (large effects missing) — Fills in missing studies on the right of the funnel; pick it when large effects are the ones likely left unpublished.

options

PET-PEESE switch leveldefault 0.05

PEESE is reported when PET's intercept differs from zero at this level (two-sided).

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

    Asymmetry tests need about 10 studies or more; with fewer, absence of evidence says little.

  • Low heterogeneity

    Strong heterogeneity can create asymmetry by itself and makes trim-and-fill unreliable.

What it reports

  • Tests: Funnel-plot asymmetry (Egger)
  • Tests: Rank correlation of effects and variances (Begg)
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
est
The average effect across studies from a meta-analysis, weighted by each study's precision.
egger_stat
Tests funnel-plot asymmetry by regressing the standardized effect on precision; a non-zero intercept means small studies differ.
egger_p
Tests funnel-plot asymmetry by regressing the standardized effect on precision; a non-zero intercept means small studies differ.
egger_bias
Tests funnel-plot asymmetry by regressing the standardized effect on precision; a non-zero intercept means small studies differ.
limit
Tests funnel-plot asymmetry by regressing the standardized effect on precision; a non-zero intercept means small studies differ.
limit_ci_low
A range of effect values compatible with your data at the chosen confidence level.
limit_ci_high
A range of effect values compatible with your data at the chosen confidence level.
begg_tau
Kendall's τ between standardized effects and their variances; a funnel-asymmetry test with lower power than Egger's.
begg_p
Kendall's τ between standardized effects and their variances; a funnel-asymmetry test with lower power than Egger's.
tf_k0
Estimates how many studies are missing from one side of the funnel, imputes their mirror images and recomputes the pooled effect.
tf_est
Estimates how many studies are missing from one side of the funnel, imputes their mirror images and recomputes the pooled effect.
tf_ci_low
A range of effect values compatible with your data at the chosen confidence level.
tf_ci_high
A range of effect values compatible with your data at the chosen confidence level.
pet
Regressions of effect size on its standard error or variance, whose intercept estimates an effect free of small-study bias.
pet_p
How surprising your data would be if the null hypothesis were true, as a probability.
peese
Regressions of effect size on its standard error or variance, whose intercept estimates an effect free of small-study bias.
peese_p
How surprising your data would be if the null hypothesis were true, as a probability.
pet_peese_est
Regressions of effect size on its standard error or variance, whose intercept estimates an effect free of small-study bias.
fsn
How many unpublished null studies would turn the combined result non-significant.
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.
tf_side
Estimates how many studies are missing from one side of the funnel, imputes their mirror images and recomputes the pooled effect.
pet_peese_use
Regressions of effect size on its standard error or variance, whose intercept estimates an effect free of small-study bias.

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

  • Egger (both variants), Begg (exact Kendall null for k < 50 without ties, tie-corrected normal otherwise — R cor.test's conventions), trim-and-fill, PET-PEESE and fail-safe N are codesplash twins.
Python

The exact script CodeSplash ran for example “Guide egger begg” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Small-study effects and publication bias
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.bias 1.0.1 · spec 408534da36a23a96
# 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 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"])
n_input = len(df)
df["study"] = pd.Categorical(df["study"], categories=["Study 01", "Study 02", "Study 03", "Study 04", "Study 05", "Study 06", "Study 07", "Study 08", "Study 09", "Study 10", "Study 11", "Study 12"])  # stored level order
df = df.dropna(subset=["study", "effect", "se"])  # listwise deletion over the analysis columns
df["study"] = df["study"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["study", "effect", "se"])  # infinite values stop the run (registry/errors.yaml)
# %% Studies
design = "generic"  # inferred from the bound columns
measure = "GEN"
cols = {
    "effect": df["effect"].to_numpy(dtype=float),
    "se": df["se"].to_numpy(dtype=float),
}
es = meta.escalc(design, measure, cols, zero_cells="only0", drop00=True, ci_level=0.95)
measure = es["measure"]
labels_all = df["study"].astype(str).tolist()
keep = es["keep"]
left_out = [labels_all[i] for i in np.flatnonzero(~keep)]
idx = np.flatnonzero(keep)
y, v = es["yi"][idx], es["vi"][idx]
labels = [labels_all[i] for i in idx]
k = len(y)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A meta-analysis", min=2, n=k)  # one usable study can't be pooled
if left_out:
    warnings.append(f"Left out ({len(left_out)}): " + ", ".join(left_out) + (" — no events (or only events) in both arms." if design == "binary" else " — effect or variance not computable."))
bt = meta.back_transform(measure)
MEASURE_LABEL = {"GEN": "effect", "LOG": "log ratio", "OR": "log odds ratio", "RR": "log risk ratio", "RD": "risk difference",
                 "MD": "mean difference", "SMD": "Hedges' g", "ZCOR": "Fisher's z", "COR": "correlation"}[measure]
RATIO = measure in ("OR", "RR", "LOG")
# What a back-transformed number is: a ratio, not a log ratio; a correlation, not Fisher's z.
DISPLAY_LABEL = {"OR": "odds ratio", "RR": "risk ratio", "LOG": "ratio", "ZCOR": "correlation"}.get(measure, MEASURE_LABEL)
if k < 3:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Testing for small-study effects", min=3, n=k)  # Egger's regression and PET-PEESE fit two coefficients
if np.all(y == y[0]):
    # Identical effects: Begg's rank correlation and the Egger / PET-PEESE regressions are undefined (an exact fit).
    cs.cs_error("CS_E_CONSTANT", column="effect")

# %% Small-study tests
conf = 0.95
tau2_method = "REML"
re = meta.rma(y, v, method=tau2_method, level=conf)
est = float(re["beta"][0])
eg = meta.egger(y, v, variant="classic", method=tau2_method, level=conf)
bg = meta.begg(y, v)
tf = meta.trimfill(y, v, method=tau2_method, side="auto", estimator="L0")
pp = meta.pet_peese(y, v, alpha=0.05, level=conf)
fs = meta.failsafe_n(y, v)
tff = tf["filled"]

# %% Assumptions
assumptions = [
    {"key": "k_studies", "label": "Enough studies", "status": "warn" if k < 10 else "pass",
     "detail": f"{k} studies" + ("; asymmetry tests have little power — a non-significant result says little." if k < 10 else ".")},
    {"key": "heterogeneity", "label": "Low heterogeneity", "status": "warn" if re["i2"] > 50 else "pass",
     "detail": f"I² = {re['i2']:.1f}%" + ("; heterogeneity alone can produce asymmetry and makes trim-and-fill unreliable." if re["i2"] > 50 else ".")},
]

# %% Result
disp = MEASURE_LABEL.replace("log ", "") if RATIO else MEASURE_LABEL
side_word = "left (smaller effects)" if tf["side"] == "left" else "right (larger effects)"
rows = [
    {"test": "Egger" + (" (classic)" if eg["variant"] == "classic" else " (meta-regression on SE)"), "statistic": eg["stat"], "p": eg["p"],
     "detail": f"limit effect {bt(eg['limit']):.3g} [{bt(eg['limit_ci_low']):.3g}, {bt(eg['limit_ci_high']):.3g}]"},
    {"test": "Begg–Mazumdar", "statistic": bg["tau"], "p": bg["p"], "detail": "exact Kendall null" if bg["exact"] else "normal approximation"},
    {"test": f"Trim-and-fill ({tf['estimator']})", "statistic": float(tf["k0"]), "p": None,
     "detail": f"{tf['k0']} imputed on the {side_word}; adjusted {bt(float(tff['beta'][0])):.3g} [{bt(float(tff['ci_low'][0])):.3g}, {bt(float(tff['ci_high'][0])):.3g}]"},
    {"test": "PET-PEESE", "statistic": pp["est"], "p": pp["pet_p"], "detail": f"{pp['use'].upper()} estimate {bt(pp['est']):.3g} [{bt(pp['ci_low']):.3g}, {bt(pp['ci_high']):.3g}]"},
    {"test": "Fail-safe N (Rosenthal)", "statistic": fs["fsn"], "p": None, "detail": f"robust if above 5k + 10 = {fs['threshold']:.0f}"},
]
all_y = np.concatenate([y, tf["fill_y"]])
all_se = np.sqrt(np.concatenate([v, tf["fill_v"]]))
cs.publish({
    "method": "meta.bias",
    "methodVersion": "1.0.1",
    "title": f"Small-study effects in {k} studies",
    "engine": cs.engine_info("numpy", "scipy"),
    "n": k,
    "summary": f"Egger {cs.fmt_p(eg['p'])}; Begg τ = {bg['tau']:.3f}, {cs.fmt_p(bg['p'])}; trim-and-fill adds {tf['k0']} (pooled {bt(est):.3g} → {bt(float(tff['beta'][0])):.3g}).",
    "apa": f"Egger's test {cs.fmt_p(eg['p'])}; Begg's τ = {cs.fmt_num(bg['tau'])}, {cs.fmt_p(bg['p'])}; trim-and-fill k₀ = {tf['k0']}",
    "statistics": [{"key": "egger_p", "label": "p (Egger)", "value": eg["p"], "format": "p"}, {"key": "begg_p", "label": "p (Begg)", "value": bg["p"], "format": "p"},
                   {"key": "tf_k0", "label": "Studies imputed", "value": tf["k0"], "format": "integer"}],
    "tables": [{"key": "tests", "title": f"Small-study diagnostics ({disp})",
                "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
                            {"key": "p", "label": "p", "type": "number"}, {"key": "detail", "label": "", "type": "string"}],
                "rows": rows}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["Asymmetry can come from publication bias, heterogeneity, chance or differences in study quality; these tests cannot tell which."],
    "charts": [cs.chart("funnel", "meta-funnel", "Funnel plot with imputed studies",
                        {"estimate": cs.col(MEASURE_LABEL, [float(t) for t in all_y]), "se": cs.col("standard error", [float(t) for t in all_se]),
                         "label": cs.col("study", labels + [f"imputed {j + 1}" for j in range(tf["k0"])]),
                         "kind": cs.col("study", ["observed"] * k + ["imputed"] * tf["k0"])},
                        controls={"center": est, "adjusted": float(tff["beta"][0]), "contours": True, "eggerIntercept": eg["limit"], "eggerSlope": eg["bias"]})],
    "values": {
        "k": k, "est": est, "egger_stat": eg["stat"], "egger_p": eg["p"], "egger_bias": eg["bias"], "limit": eg["limit"], "limit_ci_low": eg["limit_ci_low"],
        "limit_ci_high": eg["limit_ci_high"], "begg_tau": bg["tau"], "begg_p": bg["p"], "tf_k0": tf["k0"], "tf_est": float(tff["beta"][0]),
        "tf_ci_low": float(tff["ci_low"][0]), "tf_ci_high": float(tff["ci_high"][0]), "pet": pp["pet"], "pet_p": pp["pet_p"], "peese": pp["peese"],
        "peese_p": pp["peese_p"], "pet_peese_est": pp["est"], "fsn": fs["fsn"], "measure": measure, "measure_label": MEASURE_LABEL,
        "tf_side": side_word, "pet_peese_use": pp["use"],
    },
})
R

The exact script CodeSplash ran for example “Guide egger begg” · R version 4.5.1 (2025-06-13)

# Small-study effects and publication bias
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.bias 1.0.1 · spec 408534da36a23a96
# Dataset: m1_guide (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_meta_* (twins of codesplash.stats.meta)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/m1_guide.parquet", col_select = c("study", "effect", "se")))
n_input <- nrow(df)
df[["study"]] <- factor(df[["study"]], levels = c("Study 01", "Study 02", "Study 03", "Study 04", "Study 05", "Study 06", "Study 07", "Study 08", "Study 09", "Study 10", "Study 11", "Study 12"))  # stored level order
df <- df[stats::complete.cases(df[c("study", "effect", "se")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("study", "effect", "se"))  # infinite values stop the run (registry/errors.yaml)
# %% Studies
design <- "generic"  # inferred from the bound columns
measure <- "GEN"
cols <- list(
  effect = as.numeric(df[["effect"]]),
  se = as.numeric(df[["se"]]),
  NULL
)
cols <- Filter(Negate(is.null), cols)
es <- cs_meta_escalc(design, measure, cols, zero_cells = "only0", drop00 = TRUE, ci_level = 0.95)
measure <- es$measure
labels_all <- as.character(df[["study"]])
keep <- es$keep
left_out <- labels_all[!keep]
idx <- which(keep)
y <- es$yi[idx]; v <- es$vi[idx]
labels <- labels_all[idx]
k <- length(y)
if (k < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A meta-analysis", min = 2, n = k)  # one usable study can't be pooled
if (length(left_out)) {
  warnings <- c(warnings, paste0(sprintf("Left out (%d): ", length(left_out)), paste(left_out, collapse = ", "),
                                 if (design == "binary") " — no events (or only events) in both arms." else " — effect or variance not computable."))
}
bt <- cs_meta_back(measure)
MEASURE_LABEL <- c(GEN = "effect", LOG = "log ratio", OR = "log odds ratio", RR = "log risk ratio", RD = "risk difference",
                   MD = "mean difference", SMD = "Hedges' g", ZCOR = "Fisher's z", COR = "correlation")[[measure]]
RATIO <- measure %in% c("OR", "RR", "LOG")
# What a back-transformed number is: a ratio, not a log ratio; a correlation, not Fisher's z.
DISPLAY_LABEL <- if (measure %in% c("OR", "RR", "LOG", "ZCOR")) c(OR = "odds ratio", RR = "risk ratio", LOG = "ratio", ZCOR = "correlation")[[measure]] else MEASURE_LABEL
if (k < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "Testing for small-study effects", min = 3, n = k)  # Egger's regression and PET-PEESE fit two coefficients
if (all(y == y[1])) {
  # Identical effects: Begg's rank correlation and the Egger / PET-PEESE regressions are undefined (an exact fit).
  cs_error("CS_E_CONSTANT", column = "effect")
}

# %% Small-study tests
conf <- 0.95
tau2_method <- "REML"
re <- cs_meta_rma(y, v, method = tau2_method, level = conf)
est <- re$beta[1]
eg <- cs_meta_egger(y, v, variant = "classic", method = tau2_method, level = conf)
bg <- cs_meta_begg(y, v)
tf <- cs_meta_trimfill(y, v, method = tau2_method, side = "auto", estimator = "L0")
pp <- cs_meta_pet_peese(y, v, alpha = 0.05, level = conf)
fs <- cs_meta_failsafe(y, v)
tff <- tf$filled

# %% Assumptions
assumptions <- list(
  list(key = "k_studies", label = "Enough studies", status = if (k < 10) "warn" else "pass",
       detail = paste0(sprintf("%d studies", k), if (k < 10) "; asymmetry tests have little power — a non-significant result says little." else ".")),
  list(key = "heterogeneity", label = "Low heterogeneity", status = if (re$i2 > 50) "warn" else "pass",
       detail = paste0(sprintf("I² = %.1f%%", re$i2), if (re$i2 > 50) "; heterogeneity alone can produce asymmetry and makes trim-and-fill unreliable." else "."))
)

# %% Result
disp <- if (RATIO) sub("log ", "", MEASURE_LABEL) else MEASURE_LABEL
side_word <- if (tf$side == "left") "left (smaller effects)" else "right (larger effects)"
g3 <- function(x) format(signif(x, 3))
rows <- list(
  list(test = paste0("Egger", if (eg$variant == "classic") " (classic)" else " (meta-regression on SE)"), statistic = eg$stat, p = eg$p,
       detail = sprintf("limit effect %s [%s, %s]", g3(bt(eg$limit)), g3(bt(eg$limit_ci_low)), g3(bt(eg$limit_ci_high)))),
  list(test = "Begg–Mazumdar", statistic = bg$tau, p = bg$p, detail = if (bg$exact) "exact Kendall null" else "normal approximation"),
  list(test = sprintf("Trim-and-fill (%s)", tf$estimator), statistic = tf$k0, p = NULL,
       detail = sprintf("%d imputed on the %s; adjusted %s [%s, %s]", tf$k0, side_word, g3(bt(tff$beta[1])), g3(bt(tff$ci_low[1])), g3(bt(tff$ci_high[1])))),
  list(test = "PET-PEESE", statistic = pp$est, p = pp$pet_p, detail = sprintf("%s estimate %s [%s, %s]", toupper(pp$use), g3(bt(pp$est)), g3(bt(pp$ci_low)), g3(bt(pp$ci_high)))),
  list(test = "Fail-safe N (Rosenthal)", statistic = fs$fsn, p = NULL, detail = sprintf("robust if above 5k + 10 = %.0f", fs$threshold))
)
all_y <- c(y, tf$fill_y)
all_se <- sqrt(c(v, tf$fill_v))
cs_publish(list(
  method = "meta.bias",
  methodVersion = "1.0.1",
  title = sprintf("Small-study effects in %d studies", k),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = k,
  summary = sprintf("Egger %s; Begg τ = %.3f, %s; trim-and-fill adds %d (pooled %s → %s).", cs_fmt_p(eg$p), bg$tau, cs_fmt_p(bg$p), tf$k0, g3(bt(est)), g3(bt(tff$beta[1]))),
  apa = sprintf("Egger's test %s; Begg's τ = %s, %s; trim-and-fill k₀ = %d", cs_fmt_p(eg$p), cs_fmt_num(bg$tau), cs_fmt_p(bg$p), tf$k0),
  statistics = list(list(key = "egger_p", label = "p (Egger)", value = eg$p, format = "p"), list(key = "begg_p", label = "p (Begg)", value = bg$p, format = "p"),
                    list(key = "tf_k0", label = "Studies imputed", value = tf$k0, format = "integer")),
  tables = list(list(key = "tests", title = sprintf("Small-study diagnostics (%s)", disp),
                     columns = list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
                                    list(key = "p", label = "p", type = "number"), list(key = "detail", label = "", type = "string")),
                     rows = rows)),
  assumptions = assumptions,
  warnings = warnings,
  notes = list("Asymmetry can come from publication bias, heterogeneity, chance or differences in study quality; these tests cannot tell which."),
  charts = list(cs_chart("funnel", "meta-funnel", "Funnel plot with imputed studies",
                         list(estimate = cs_col(MEASURE_LABEL, all_y), se = cs_col("standard error", all_se),
                              label = cs_col("study", c(labels, if (tf$k0 > 0) sprintf("imputed %d", seq_len(tf$k0)) else character(0))),
                              kind = cs_col("study", c(rep("observed", k), rep("imputed", tf$k0)))),
                         controls = list(center = est, adjusted = tff$beta[1], contours = TRUE, eggerIntercept = eg$limit, eggerSlope = eg$bias))),
  values = list(
    k = k, est = est, egger_stat = eg$stat, egger_p = eg$p, egger_bias = eg$bias, limit = eg$limit, limit_ci_low = eg$limit_ci_low,
    limit_ci_high = eg$limit_ci_high, begg_tau = bg$tau, begg_p = bg$p, tf_k0 = tf$k0, tf_est = tff$beta[1], tf_ci_low = tff$ci_low[1],
    tf_ci_high = tff$ci_high[1], pet = pp$pet, pet_p = pp$pet_p, peese = pp$peese, peese_p = pp$peese_p, pet_peese_est = pp$est, fsn = fs$fsn,
    measure = measure, measure_label = MEASURE_LABEL, tf_side = side_word, pet_peese_use = pp$use
  )
))

Sources

  • Egger, M., Davey Smith, G., Schneider, M., & Minder, C. (1997). Bias in meta-analysis detected by a simple, graphical test. BMJ, 315, 629–634.
  • Begg, C. B., & Mazumdar, M. (1994). Operating characteristics of a rank correlation test for publication bias. Biometrics, 50, 1088–1101.
  • Duval, S., & Tweedie, R. (2000). Trim and fill. Biometrics, 56, 455–463.
  • Stanley, T. D., & Doucouliagos, H. (2014). Meta-regression approximations to reduce publication selection bias. Research Synthesis Methods, 5, 60–78.
  • Rosenthal, R. (1979). The file drawer problem and tolerance for null results. Psychological Bulletin, 86, 638–641.
  • Sterne, J. A. C., et al. (2011). Recommendations for examining and interpreting funnel plot asymmetry. BMJ, 343, d4002.

From the CodeSplash method registry · meta.bias v1.0.1.