Skip to content

BMeta-analysis · meta.bayes

Bayesian random-effects meta-analysis

Given the studies and a stated prior, what are the plausible values of the average effect and of the spread of true effects?

The normal–normal hierarchical model with a flat or normal prior on the average effect μ and a half-normal, half-Cauchy, exponential, uniform, Jeffreys or flat prior on the heterogeneity τ. The posterior comes from deterministic quadrature over τ (no Markov chains, so every run gives the same numbers): medians and credible intervals for μ, τ, I², a new study's effect and each study's shrunken effect, the probability that μ is above zero, and Savage–Dickey Bayes factors for τ = 0 and μ = 0 when those priors are proper. With few studies the τ prior shapes the answer, so state it.

Experimental Python and R agree to 6 decimals Also called Bayesian meta-analysis, bayesmeta, normal–normal hierarchical model…

A real result

Example “Crins hn normal”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Bayesian meta-analysis of 6 studiesRecorded · Python and R agreeRecorded 2026-11-17 · 35 values compared
R

odds ratio = 0.21, 95% CrI [0.11, 0.39]; τ = 0.34, 95% CrI [0.02, 0.97]

Average odds ratio (median)
0.2073
τ (median)
0.3445
P(μ > 0)
6.013e-5
I² (%)
21.723

Effect size

  • Average odds ratio 0.2073 95% CI [0.1067, 0.3932]

Plots

Shrunken study effects and the average effectHow do the studies' effects compare, and what is the pooled effect and its spread?
View data
odds ratiohighrowstudylow
0.17520.3547studyHeffron (2003)0.0664
0.27760.7870studyGibelli (2004)0.1364
0.18910.4246studySchuller (2005)0.0644
0.19580.3738studyGanschow (2005)0.0962
0.22250.5243studySpada (2006)0.1041
0.19930.5243studyGras (2008)0.0618
0.20730.3932summaryμ (posterior)0.1067
Posterior of μ (log odds ratio)How did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensityμ (log odds ratio)
posterior0.0030−2.890
posterior0.0032−2.877
posterior0.0035−2.865
posterior0.0038−2.852
posterior0.0041−2.839
posterior0.0044−2.826
posterior0.0048−2.813
posterior0.0052−2.801
posterior0.0056−2.788
posterior0.0060−2.775
posterior0.0065−2.762
posterior0.0070−2.750
posterior0.0076−2.737
posterior0.0082−2.724
posterior0.0088−2.711
posterior0.0095−2.698
posterior0.0103−2.686
posterior0.0111−2.673
posterior0.0120−2.660
posterior0.0130−2.647
posterior0.0140−2.635
posterior0.0151−2.622
posterior0.0163−2.609
posterior0.0177−2.596
posterior0.0191−2.583
posterior0.0206−2.571
posterior0.0222−2.558
posterior0.0240−2.545
posterior0.0259−2.532
posterior0.0280−2.520
posterior0.0302−2.507
posterior0.0326−2.494
posterior0.0352−2.481
posterior0.0381−2.468
posterior0.0411−2.456
posterior0.0443−2.443
posterior0.0478−2.430
posterior0.0516−2.417
posterior0.0557−2.405
posterior0.0601−2.392
posterior0.0648−2.379
posterior0.0699−2.366
posterior0.0753−2.353
posterior0.0812−2.341
posterior0.0875−2.328
posterior0.0942−2.315
posterior0.1015−2.302
posterior0.1092−2.290
posterior0.1175−2.277
posterior0.1264−2.264
posterior0.1358−2.251
posterior0.1459−2.238
posterior0.1567−2.226
posterior0.1681−2.213
posterior0.1803−2.200
posterior0.1933−2.187
posterior0.2070−2.175
posterior0.2215−2.162
posterior0.2369−2.149
posterior0.2531−2.136

First 60 of 402 rows.

Posterior of τHow did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensityτ
posterior1.4090
posterior1.4090.0060
posterior1.4100.0121
posterior1.4100.0181
posterior1.4110.0241
posterior1.4120.0301
posterior1.4130.0362
posterior1.4140.0422
posterior1.4150.0482
posterior1.4170.0542
posterior1.4190.0603
posterior1.4210.0663
posterior1.4230.0723
posterior1.4250.0784
posterior1.4270.0844
posterior1.4290.0904
posterior1.4320.0964
posterior1.4340.1025
posterior1.4370.1085
posterior1.4400.1145
posterior1.4420.1205
posterior1.4450.1266
posterior1.4480.1326
posterior1.4510.1386
posterior1.4540.1446
posterior1.4560.1507
posterior1.4590.1567
posterior1.4620.1627
posterior1.4640.1688
posterior1.4670.1748
posterior1.4690.1808
posterior1.4720.1868
posterior1.4740.1929
posterior1.4760.1989
posterior1.4770.2049
posterior1.4790.2109
posterior1.4800.2170
posterior1.4810.2230
posterior1.4820.2290
posterior1.4830.2351
posterior1.4830.2411
posterior1.4830.2471
posterior1.4830.2531
posterior1.4820.2592
posterior1.4820.2652
posterior1.4800.2712
posterior1.4790.2772
posterior1.4770.2833
posterior1.4750.2893
posterior1.4720.2953
posterior1.4690.3014
posterior1.4650.3074
posterior1.4610.3134
posterior1.4570.3194
posterior1.4520.3255
posterior1.4470.3315
posterior1.4420.3375
posterior1.4360.3435
posterior1.4290.3496
posterior1.4220.3556

First 60 of 402 rows.

Assumptions

  • Prior stated and checked — 6 studies with a half-normal (scale 0.5) prior on τ; rerun with another τ prior to see how much it matters.
  • Prior scale fits the measure — τ is on the log odds ratio scale.
  • Independent estimates — One estimate per study is assumed; several outcomes from one study need a multilevel model.

Posterior (95% central credible intervals; priors: τ half-normal (scale 0.5), μ normal (mean 0, SD 4))

MedianMeanLowerUpper
μ (average odds ratio)0.2073—0.10670.3932
τ (heterogeneity)0.3445—0.01770.9730
I² (%)21.723—0.073568.882
θ (a new study's odds ratio)0.2080—0.06250.6588

Study effects shrunken towards μ (odds ratio; posterior median, 95% central interval)

StudyObservedShrunkenLowerUpper
Heffron (2003)0.09930.17520.06640.3547
Gibelli (2004)0.63160.27760.13640.7870
Schuller (2005)0.10000.18910.06440.4246
Ganschow (2005)0.17240.19580.09620.3738
Spada (2006)0.28410.22250.10410.5243
Gras (2008)0.08910.19930.06180.5243

Posterior probability and Bayes factors

Value
P(μ > 0 | data) (ratio above 1)6.013e-5
BF₀₁ for τ = 0 (no heterogeneity)0.8832
BF₀₁ for μ = 0 (no average effect)0.0038
  • Priors: τ half-normal (scale 0.5); μ normal (mean 0, SD 4). Credible intervals are central.
  • Bayes factors use the Savage–Dickey ratio (posterior over prior density at the null) and are shown only when that prior is proper; BF₀₁ above 1 favors the null.
Python

odds ratio = 0.21, 95% CrI [0.11, 0.39]; τ = 0.34, 95% CrI [0.02, 0.97]

Average odds ratio (median)
0.2073
τ (median)
0.3445
P(μ > 0)
6.013e-5
I² (%)
21.723

Effect size

  • Average odds ratio 0.2073 95% CI [0.1067, 0.3932]

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

Assumptions

  • Prior stated and checked — 6 studies with a half-normal (scale 0.5) prior on τ; rerun with another τ prior to see how much it matters.
  • Prior scale fits the measure — τ is on the log odds ratio scale.
  • Independent estimates — One estimate per study is assumed; several outcomes from one study need a multilevel model.

Posterior (95% central credible intervals; priors: τ half-normal (scale 0.5), μ normal (mean 0, SD 4))

MedianMeanLowerUpper
μ (average odds ratio)0.2073—0.10670.3932
τ (heterogeneity)0.3445—0.01770.9730
I² (%)21.723—0.073568.882
θ (a new study's odds ratio)0.2080—0.06250.6588

Study effects shrunken towards μ (odds ratio; posterior median, 95% central interval)

StudyObservedShrunkenLowerUpper
Heffron (2003)0.09930.17520.06640.3547
Gibelli (2004)0.63160.27760.13640.7870
Schuller (2005)0.10000.18910.06440.4246
Ganschow (2005)0.17240.19580.09620.3738
Spada (2006)0.28410.22250.10410.5243
Gras (2008)0.08910.19930.06180.5243

Posterior probability and Bayes factors

Value
P(μ > 0 | data) (ratio above 1)6.013e-5
BF₀₁ for τ = 0 (no heterogeneity)0.8832
BF₀₁ for μ = 0 (no average effect)0.0038
  • Priors: τ half-normal (scale 0.5); μ normal (mean 0, SD 4). Credible intervals are central.
  • Bayes factors use the Savage–Dickey ratio (posterior over prior density at the null) and are shown only when that prior is proper; BF₀₁ above 1 favors the null.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Crins hn normallb1_crins · events_1: events_1 · events_2: events_2 · study: publication · total_1: total_1 · total_2: total_2
  • Crins shortestlb1_crins · events_1: events_1 · events_2: events_2 · study: publication · total_1: total_1 · total_2: total_2
  • Hackshaw ratio hnm1_hackshaw · ci_high: or_high · ci_low: or_low · effect: or · study: study
  • Bcg rr exponentialm1_bcg · events_1: events_1 · events_2: events_2 · study: trial · total_1: total_1 · total_2: total_2
  • Normand smd uniformm1_normand · mean_1: mean_1 · mean_2: mean_2 · sd_1: sd_1 · sd_2: sd_2 · study: source · total_1: total_1 · total_2: total_2
  • Guide jeffreysm1_guide · effect: effect · se: se · study: study
  • Raudenbush flatm1_raudenbush · effect: effect · se: se · study: study
  • Degenerate n1lb1_crins · events_1: events_1 · events_2: events_2 · study: publication · total_1: total_1 · total_2: total_2

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.
Prior on τ (heterogeneity)default half_normal

How large you expect the spread of true effects to be before seeing the data; it matters most with few studies.

  • Half-normal(default) — Weakly informative; scale 0.5 suits log odds ratios and SMDs (Röver et al. 2021). The usual default.
  • Half-Cauchy — Heavier tail than the half-normal, so large heterogeneity stays plausible (Gelman 2006).
  • Exponential — Mean equal to the scale; puts most weight near zero heterogeneity.
  • Uniform (0 to an upper bound) — Every τ up to the bound is equally likely; the bound is the scale below.
  • Jeffreys (improper) — A non-informative prior built from the study variances; needs at least three studies.
  • Flat (improper) — Flat on τ; can overstate heterogeneity with few studies, and needs at least three.
Prior scale for τdefault 0.5

On the analysis scale (log ratio, SMD, Fisher's z). Raw mean or risk differences need a scale in their own units.

Prior on μ (average effect)default flat

A flat prior lets the data alone locate μ; a normal prior adds outside information or mild regularization.

  • Flat (improper)(default) — No prior information about μ; the posterior median lands close to the usual random-effects estimate.
  • Normal — A center and SD you choose; needed for a Bayes factor about μ = 0.
Prior mean of μdefault 0

Center of the normal prior on the analysis scale (0 = no effect).

Prior SD of μdefault 4

Spread of the normal prior; 4 on the log odds ratio scale is barely informative.

Credible leveldefault 0.95

Posterior probability inside each interval: 0.95 gives 95% credible intervals. Higher levels mean wider intervals.

statistics

Credible intervaldefault central

Central intervals cut equal tails; shortest intervals are the narrowest range with the stated probability.

  • Central (equal tails)(default) — Cuts the same probability from each tail; the usual choice in reports.
  • Shortest (highest density) — The narrowest range with the stated probability (bayesmeta's default); for τ it often starts at 0.

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 (the question is worth pooling).

  • Independent estimates

    One estimate per study; several outcomes or arms from one study need a multilevel model.

  • Normal modelNot checked from data: state why it holds

    Sampling errors and the studies' true effects are taken as normal on the analysis scale.

  • Prior stated and checked

    With few studies the τ prior moves the answer; report it and rerun with another prior.

  • Prior scale fits the measure

    A τ prior chosen for standardized effects is too narrow or too wide for effects in raw units.

What it reports

k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
mu_mean
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
mu_sd
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
mu_median
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
mu_low
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
mu_high
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
mu_median_bt
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
mu_low_bt
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
mu_high_bt
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
tau_median
What the studies and the prior together say about the spread τ of true effects, summarized by its median, mode and interval.
tau_mode
What the studies and the prior together say about the spread τ of true effects, summarized by its median, mode and interval.
tau_low
A range of effect values compatible with your data at the chosen confidence level.
tau_high
A range of effect values compatible with your data at the chosen confidence level.
i2_median
What the studies and the prior together say about the spread τ of true effects, summarized by its median, mode and interval.
i2_low
A range of effect values compatible with your data at the chosen confidence level.
i2_high
A range of effect values compatible with your data at the chosen confidence level.
pred_median
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
pred_low
A range of effect values compatible with your data at the chosen confidence level.
pred_high
A range of effect values compatible with your data at the chosen confidence level.
pred_median_bt
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
pred_low_bt
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
pred_high_bt
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
p_mu_positive
The share of the posterior for the average effect μ that lies above zero (above 1 for ratios).
bf01_tau
How much more likely the studies are with τ = 0 (or μ = 0) than under the prior, from posterior over prior density at that value.
bf01_mu
How much more likely the studies are with τ = 0 (or μ = 0) than under the prior, from posterior over prior density at that value.
theta_mean
A panel model that treats unit differences as noise unrelated to the regressors, which gives more precise estimates when that holds.
theta_low
A range of effect values compatible with your data at the chosen confidence level.
theta_high
A range of effect values compatible with your data at the chosen confidence level.
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.
effect_label
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
tau_prior_label
A prior for the heterogeneity τ that keeps it positive and favors small values; its scale sets how large τ is likely to be.
mu_prior_label
A prior for the heterogeneity τ that keeps it positive and favors small values; its scale sets how large τ is likely to be.
interval_label
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.
cred_level
A range that holds the average effect μ with the stated posterior probability, given the studies and the priors.

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • The marginal posterior of τ (median, intervals, density at 0 and so the τ = 0 Bayes factor) agrees with bayesmeta 3.5 to about 1e-12: both integrate the same density, here with fixed Gauss–Legendre panels on log τ.
  • μ, a new study's θ and the shrunken θ_i differ from bayesmeta by up to about 3e-3: bayesmeta approximates their mixture over τ with the DIRECT grid (about 17 support points), the twins sum over every quadrature node (about 4,000). A brute-force double integral agrees with the twins to 1e-7 (tests/crosscheck/w3lb1_meta_lab.R).
Python

The exact script CodeSplash ran for example “Crins hn normal” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Bayesian random-effects meta-analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.bayes 1.0.2 · spec ab1c824d53ece71a
# Dataset: lb1_crins (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  # effect sizes (twins of codesplashr::cs_meta_*)
from codesplash.stats import meta_lab  # Bayesian meta-analysis (twin of codesplashr::cs_meta_bayes)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/lb1_crins.parquet", columns=["publication", "events_1", "total_1", "events_2", "total_2"])
n_input = len(df)
df["publication"] = pd.Categorical(df["publication"], categories=["Heffron (2003)", "Gibelli (2004)", "Schuller (2005)", "Ganschow (2005)", "Spada (2006)", "Gras (2008)"])  # stored level order
df = df.dropna(subset=["publication", "events_1", "total_1", "events_2", "total_2"])  # listwise deletion over the analysis columns
df["publication"] = df["publication"].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, ["publication", "events_1", "total_1", "events_2", "total_2"])  # infinite values stop the run (registry/errors.yaml)
# %% Studies
design = "binary"  # inferred from the bound columns
measure = "OR"
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["publication"].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)

# %% Priors
conf = 0.95
tau_prior = "half_normal"
tau_scale = 0.5
mu_prior = (0, 4)  # normal prior on μ (analysis scale)
interval = "central"
scaled = tau_prior in ("half_normal", "half_cauchy", "exponential", "uniform")
TAU_LABEL = meta_lab.TAU_PRIOR_LABELS[tau_prior] + (f" ({'upper bound' if tau_prior == 'uniform' else 'scale'} {tau_scale:g})" if scaled else "")
MU_LABEL = f"normal (mean {mu_prior[0]:g}, SD {mu_prior[1]:g})" if mu_prior else "flat"

# %% Posterior (deterministic quadrature over τ; no Markov chains)
fit = meta_lab.bayes(y, v, tau_prior=tau_prior, tau_scale=tau_scale, mu_prior=mu_prior, level=conf, interval=interval)
theta = fit["theta"]

# %% Assumptions
raw_units = measure in ("MD", "RD", "COR")
assumptions = [
    {"key": "prior_sensitivity", "label": "Prior stated and checked", "status": "warn" if k < 5 else "info",
     "detail": f"{k} studies with a {TAU_LABEL} prior on τ" + ("; with this few studies the prior moves the answer — rerun with another prior and report both." if k < 5 else "; rerun with another τ prior to see how much it matters.")},
    {"key": "prior_scale", "label": "Prior scale fits the measure", "status": "warn" if scaled and raw_units else "pass",
     "detail": (f"The τ prior scale {tau_scale:g} is in the units of the {MEASURE_LABEL}; check it matches plausible heterogeneity in those units." if scaled and raw_units
                else f"τ is on the {MEASURE_LABEL} scale.")},
    {"key": "independence", "label": "Independent estimates", "status": "info", "detail": "One estimate per study is assumed; several outcomes from one study need a multilevel model."},
]

# %% Result
level_txt = f"{conf:.0%}"
kind_txt = "central" if interval == "central" else "shortest"
nan = lambda x: None if x is None or (isinstance(x, float) and math.isnan(x)) else x  # noqa: E731
rows_post = [
    {"quantity": f"μ (average {DISPLAY_LABEL})", "median": float(bt(fit["mu_median"])), "mean": fit["mu_mean"] if not RATIO and measure != "ZCOR" else None,
     "low": float(bt(fit["mu_low"])), "high": float(bt(fit["mu_high"]))},
    {"quantity": "τ (heterogeneity)", "median": fit["tau_median"], "mean": None, "low": fit["tau_low"], "high": fit["tau_high"]},
    {"quantity": "I² (%)", "median": fit["i2_median"], "mean": None, "low": fit["i2_low"], "high": fit["i2_high"]},
    {"quantity": f"θ (a new study's {DISPLAY_LABEL})", "median": float(bt(fit["pred_median"])), "mean": None,
     "low": float(bt(fit["pred_low"])), "high": float(bt(fit["pred_high"]))},
]
rows_theta = [{"study": labels[i], "observed": float(bt(y[i])), "median": float(bt(theta[i]["median"])),
               "low": float(bt(theta[i]["low"])), "high": float(bt(theta[i]["high"]))} for i in range(k)]
above = "1" if RATIO else "0"
rows_ev = [
    {"quantity": f"P(μ > 0 | data)" + (" (ratio above 1)" if RATIO else ""), "value": fit["p_mu_positive"]},
    {"quantity": "BF₀₁ for τ = 0 (no heterogeneity)", "value": nan(fit["bf01_tau"])},
    {"quantity": "BF₀₁ for μ = 0 (no average effect)", "value": nan(fit["bf01_mu"])},
]
g = fit["grid"]
forest = {
    "label": cs.col("study", labels + ["μ (posterior)"]),
    "estimate": cs.col(DISPLAY_LABEL, [r["median"] for r in rows_theta] + [float(bt(fit["mu_median"]))]),
    "low": cs.col("low", [r["low"] for r in rows_theta] + [float(bt(fit["mu_low"]))]),
    "high": cs.col("high", [r["high"] for r in rows_theta] + [float(bt(fit["mu_high"]))]),
    "kind": cs.col("row", ["study"] * k + ["summary"]),
}


def density_chart(key, title, x, post, prior, lo, hi, point):
    has_prior = bool(np.all(np.isfinite(prior)))
    xs = [float(t) for t in x] + ([float(t) for t in x] if has_prior else [])
    ds = [float(t) for t in post] + ([float(t) for t in prior] if has_prior else [])
    cv = ["posterior"] * len(x) + (["prior"] * len(x) if has_prior else [])
    return cs.chart(key, "prior-posterior", title, {"x": cs.col(title.split(" of ")[-1], xs), "density": cs.col("density", ds), "curve": cs.col("curve", cv)},
                    controls={"point": point, "ci_low": float(lo), "ci_high": float(hi), "cred": conf, "bf10": 0})


charts = [
    cs.chart("forest", "forest-meta", "Shrunken study effects and the average effect", forest,
             controls={"reference": 1 if RATIO else 0, "log": RATIO, "piLow": float(bt(fit["pred_low"])), "piHigh": float(bt(fit["pred_high"]))}),
    density_chart("mu", f"Posterior of μ ({MEASURE_LABEL})", g["mu"], g["mu_density"], g["mu_prior"], fit["mu_low"], fit["mu_high"], 0.0),
    density_chart("tau", "Posterior of τ", g["tau"], g["tau_density"], g["tau_prior"], fit["tau_low"], fit["tau_high"], 0.0),
]
cs.publish({
    "method": "meta.bayes",
    "methodVersion": "1.0.2",
    "title": f"Bayesian meta-analysis of {k} studies",
    "engine": cs.engine_info("numpy", "scipy"),
    "n": k,
    "summary": f"Average {DISPLAY_LABEL} {bt(fit['mu_median']):.3g} ({level_txt} credible interval [{bt(fit['mu_low']):.3g}, {bt(fit['mu_high']):.3g}]); τ = {fit['tau_median']:.3g} [{fit['tau_low']:.3g}, {fit['tau_high']:.3g}]; P(μ > 0) = {fit['p_mu_positive']:.3f}.",
    "apa": f"{DISPLAY_LABEL} = {cs.fmt_num(float(bt(fit['mu_median'])))}, {level_txt} CrI [{cs.fmt_num(float(bt(fit['mu_low'])))}, {cs.fmt_num(float(bt(fit['mu_high'])))}]; τ = {cs.fmt_num(fit['tau_median'])}, {level_txt} CrI [{cs.fmt_num(fit['tau_low'])}, {cs.fmt_num(fit['tau_high'])}]",
    "statistics": [
        {"key": "mu_median_bt", "label": f"Average {DISPLAY_LABEL} (median)", "value": float(bt(fit["mu_median"]))},
        {"key": "tau_median", "label": "τ (median)", "value": fit["tau_median"]},
        {"key": "p_mu_positive", "label": "P(μ > 0)", "value": fit["p_mu_positive"]},
        {"key": "i2_median", "label": "I² (%)", "value": fit["i2_median"]},
    ],
    "tables": [
        {"key": "posterior", "title": f"Posterior ({level_txt} {kind_txt} credible intervals; priors: τ {TAU_LABEL}, μ {MU_LABEL})",
         "columns": [{"key": "quantity", "label": "", "type": "string"}, {"key": "median", "label": "Median", "type": "number"},
                     {"key": "mean", "label": "Mean", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"},
                     {"key": "high", "label": "Upper", "type": "number"}],
         "rows": rows_post},
        {"key": "shrinkage", "title": f"Study effects shrunken towards μ ({DISPLAY_LABEL}; posterior median, {level_txt} central interval)",
         "columns": [{"key": "study", "label": "Study", "type": "string"}, {"key": "observed", "label": "Observed", "type": "number"},
                     {"key": "median", "label": "Shrunken", "type": "number"}, {"key": "low", "label": "Lower", "type": "number"},
                     {"key": "high", "label": "Upper", "type": "number"}],
         "rows": rows_theta},
        {"key": "evidence", "title": "Posterior probability and Bayes factors",
         "columns": [{"key": "quantity", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
         "rows": rows_ev},
    ],
    "effectSizes": [{"key": "mu_median_bt", "label": f"Average {DISPLAY_LABEL}", "value": float(bt(fit["mu_median"])), "ciLow": float(bt(fit["mu_low"])),
                     "ciHigh": float(bt(fit["mu_high"])), "ciLevel": conf, "method": f"Bayesian random effects ({kind_txt} credible interval)"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Priors: τ {TAU_LABEL}; μ {MU_LABEL}. Credible intervals are {kind_txt}.",
              "Bayes factors use the Savage–Dickey ratio (posterior over prior density at the null) and are shown only when that prior is proper; BF₀₁ above 1 favors the null."],
    "charts": charts,
    "values": {
        "k": k, "mu_mean": fit["mu_mean"], "mu_sd": fit["mu_sd"], "mu_median": fit["mu_median"], "mu_low": fit["mu_low"], "mu_high": fit["mu_high"],
        "mu_median_bt": float(bt(fit["mu_median"])), "mu_low_bt": float(bt(fit["mu_low"])), "mu_high_bt": float(bt(fit["mu_high"])),
        "tau_median": fit["tau_median"], "tau_mode": float(fit["tau_mode"]), "tau_low": fit["tau_low"], "tau_high": fit["tau_high"],
        "i2_median": fit["i2_median"], "i2_low": fit["i2_low"], "i2_high": fit["i2_high"],
        "pred_median": fit["pred_median"], "pred_low": fit["pred_low"], "pred_high": fit["pred_high"],
        "pred_median_bt": float(bt(fit["pred_median"])), "pred_low_bt": float(bt(fit["pred_low"])), "pred_high_bt": float(bt(fit["pred_high"])),
        "p_mu_positive": fit["p_mu_positive"], "bf01_tau": fit["bf01_tau"], "bf01_mu": fit["bf01_mu"],
        "theta_mean": [t["mean"] for t in theta], "theta_low": [t["low"] for t in theta], "theta_high": [t["high"] for t in theta],
        "measure": measure, "measure_label": MEASURE_LABEL, "effect_label": DISPLAY_LABEL, "tau_prior_label": TAU_LABEL, "mu_prior_label": MU_LABEL,
        "interval_label": kind_txt, "cred_level": conf,
    },
})
R

The exact script CodeSplash ran for example “Crins hn normal” · R version 4.5.1 (2025-06-13)

# Bayesian random-effects meta-analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.bayes 1.0.2 · spec ab1c824d53ece71a
# Dataset: lb1_crins (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_escalc, cs_meta_bayes (twins of codesplash.stats.meta / meta_lab)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/lb1_crins.parquet", col_select = c("publication", "events_1", "total_1", "events_2", "total_2")))
n_input <- nrow(df)
df[["publication"]] <- factor(df[["publication"]], levels = c("Heffron (2003)", "Gibelli (2004)", "Schuller (2005)", "Ganschow (2005)", "Spada (2006)", "Gras (2008)"))  # stored level order
df <- df[stats::complete.cases(df[c("publication", "events_1", "total_1", "events_2", "total_2")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("publication", "events_1", "total_1", "events_2", "total_2"))  # infinite values stop the run (registry/errors.yaml)
# %% Studies
design <- "binary"  # inferred from the bound columns
measure <- "OR"
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[["publication"]])
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

# %% Priors
conf <- 0.95
tau_prior <- "half_normal"
tau_scale <- 0.5
mu_prior <- c(0, 4) # normal prior on μ (analysis scale)
interval <- "central"
scaled <- tau_prior %in% c("half_normal", "half_cauchy", "exponential", "uniform")
TAU_LABEL <- paste0(cs_meta_tau_prior_labels[[tau_prior]],
                    if (scaled) sprintf(" (%s %s)", if (tau_prior == "uniform") "upper bound" else "scale", sprintf("%g", tau_scale)) else "")
MU_LABEL <- if (!is.null(mu_prior)) sprintf("normal (mean %s, SD %s)", sprintf("%g", mu_prior[1]), sprintf("%g", mu_prior[2])) else "flat"

# %% Posterior (deterministic quadrature over τ; no Markov chains)
fit <- cs_meta_bayes(y, v, tau_prior = tau_prior, tau_scale = tau_scale, mu_prior = mu_prior, level = conf, interval = interval)
theta <- fit$theta

# %% Assumptions
raw_units <- measure %in% c("MD", "RD", "COR")
assumptions <- list(
  list(key = "prior_sensitivity", label = "Prior stated and checked", status = if (k < 5) "warn" else "info",
       detail = paste0(sprintf("%d studies with a %s prior on τ", k, TAU_LABEL),
                       if (k < 5) "; with this few studies the prior moves the answer — rerun with another prior and report both." else "; rerun with another τ prior to see how much it matters.")),
  list(key = "prior_scale", label = "Prior scale fits the measure", status = if (scaled && raw_units) "warn" else "pass",
       detail = if (scaled && raw_units) sprintf("The τ prior scale %s is in the units of the %s; check it matches plausible heterogeneity in those units.", sprintf("%g", tau_scale), MEASURE_LABEL)
                else sprintf("τ is on the %s scale.", MEASURE_LABEL)),
  list(key = "independence", label = "Independent estimates", status = "info", detail = "One estimate per study is assumed; several outcomes from one study need a multilevel model.")
)

# %% Result
level_txt <- sprintf("%.0f%%", conf * 100)
kind_txt <- if (interval == "central") "central" else "shortest"
na_or <- function(x) if (is.na(x)) NULL else x
g3 <- function(x) format(signif(x, 3))
rows_post <- list(
  list(quantity = sprintf("μ (average %s)", DISPLAY_LABEL), median = bt(fit$mu_median), mean = if (!RATIO && measure != "ZCOR") fit$mu_mean else NULL,
       low = bt(fit$mu_low), high = bt(fit$mu_high)),
  list(quantity = "τ (heterogeneity)", median = fit$tau_median, mean = NULL, low = fit$tau_low, high = fit$tau_high),
  list(quantity = "I² (%)", median = fit$i2_median, mean = NULL, low = fit$i2_low, high = fit$i2_high),
  list(quantity = sprintf("θ (a new study's %s)", DISPLAY_LABEL), median = bt(fit$pred_median), mean = NULL, low = bt(fit$pred_low), high = bt(fit$pred_high))
)
rows_theta <- lapply(seq_len(k), function(i) list(study = labels[i], observed = bt(y[i]), median = bt(theta[[i]]$median),
                                                  low = bt(theta[[i]]$low), high = bt(theta[[i]]$high)))
rows_ev <- list(
  list(quantity = paste0("P(μ > 0 | data)", if (RATIO) " (ratio above 1)" else ""), value = fit$p_mu_positive),
  list(quantity = "BF₀₁ for τ = 0 (no heterogeneity)", value = na_or(fit$bf01_tau)),
  list(quantity = "BF₀₁ for μ = 0 (no average effect)", value = na_or(fit$bf01_mu))
)
gr <- fit$grid
th_med <- vapply(theta, function(t) t$median, numeric(1))
th_lo <- vapply(theta, function(t) t$low, numeric(1))
th_hi <- vapply(theta, function(t) t$high, numeric(1))
forest <- list(
  label = cs_col("study", c(labels, "μ (posterior)")),
  estimate = cs_col(DISPLAY_LABEL, c(bt(th_med), bt(fit$mu_median))),
  low = cs_col("low", c(bt(th_lo), bt(fit$mu_low))),
  high = cs_col("high", c(bt(th_hi), bt(fit$mu_high))),
  kind = cs_col("row", c(rep("study", k), "summary"))
)
density_chart <- function(key, title, x, post, prior, lo, hi, point) {
  has_prior <- all(is.finite(prior))
  xs <- c(x, if (has_prior) x)
  ds <- c(post, if (has_prior) prior)
  cv <- c(rep("posterior", length(x)), if (has_prior) rep("prior", length(x)))
  name <- sub(".* of ", "", title)
  cs_chart(key, "prior-posterior", title, list(x = cs_col(name, xs), density = cs_col("density", ds), curve = cs_col("curve", cv)),
           controls = list(point = point, ci_low = lo, ci_high = hi, cred = conf, bf10 = 0))
}
charts <- list(
  cs_chart("forest", "forest-meta", "Shrunken study effects and the average effect", forest,
           controls = list(reference = if (RATIO) 1 else 0, log = RATIO, piLow = bt(fit$pred_low), piHigh = bt(fit$pred_high))),
  density_chart("mu", sprintf("Posterior of μ (%s)", MEASURE_LABEL), gr$mu, gr$mu_density, gr$mu_prior, fit$mu_low, fit$mu_high, 0),
  density_chart("tau", "Posterior of τ", gr$tau, gr$tau_density, gr$tau_prior, fit$tau_low, fit$tau_high, 0)
)
cs_publish(list(
  method = "meta.bayes",
  methodVersion = "1.0.2",
  title = sprintf("Bayesian meta-analysis of %d studies", k),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = k,
  summary = sprintf("Average %s %s (%s credible interval [%s, %s]); τ = %s [%s, %s]; P(μ > 0) = %.3f.", DISPLAY_LABEL, g3(bt(fit$mu_median)), level_txt,
                    g3(bt(fit$mu_low)), g3(bt(fit$mu_high)), g3(fit$tau_median), g3(fit$tau_low), g3(fit$tau_high), fit$p_mu_positive),
  apa = sprintf("%s = %s, %s CrI [%s, %s]; τ = %s, %s CrI [%s, %s]", DISPLAY_LABEL, cs_fmt_num(bt(fit$mu_median)), level_txt, cs_fmt_num(bt(fit$mu_low)),
                cs_fmt_num(bt(fit$mu_high)), cs_fmt_num(fit$tau_median), level_txt, cs_fmt_num(fit$tau_low), cs_fmt_num(fit$tau_high)),
  statistics = list(
    list(key = "mu_median_bt", label = sprintf("Average %s (median)", DISPLAY_LABEL), value = bt(fit$mu_median)),
    list(key = "tau_median", label = "τ (median)", value = fit$tau_median),
    list(key = "p_mu_positive", label = "P(μ > 0)", value = fit$p_mu_positive),
    list(key = "i2_median", label = "I² (%)", value = fit$i2_median)
  ),
  tables = list(
    list(key = "posterior", title = sprintf("Posterior (%s %s credible intervals; priors: τ %s, μ %s)", level_txt, kind_txt, TAU_LABEL, MU_LABEL),
         columns = list(list(key = "quantity", label = "", type = "string"), list(key = "median", label = "Median", type = "number"),
                        list(key = "mean", label = "Mean", type = "number"), list(key = "low", label = "Lower", type = "number"),
                        list(key = "high", label = "Upper", type = "number")),
         rows = rows_post),
    list(key = "shrinkage", title = sprintf("Study effects shrunken towards μ (%s; posterior median, %s central interval)", DISPLAY_LABEL, level_txt),
         columns = list(list(key = "study", label = "Study", type = "string"), list(key = "observed", label = "Observed", type = "number"),
                        list(key = "median", label = "Shrunken", type = "number"), list(key = "low", label = "Lower", type = "number"),
                        list(key = "high", label = "Upper", type = "number")),
         rows = rows_theta),
    list(key = "evidence", title = "Posterior probability and Bayes factors",
         columns = list(list(key = "quantity", label = "", type = "string"), list(key = "value", label = "Value", type = "number")),
         rows = rows_ev)
  ),
  effectSizes = list(list(key = "mu_median_bt", label = sprintf("Average %s", DISPLAY_LABEL), value = bt(fit$mu_median), ciLow = bt(fit$mu_low),
                          ciHigh = bt(fit$mu_high), ciLevel = conf, method = sprintf("Bayesian random effects (%s credible interval)", kind_txt))),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Priors: τ %s; μ %s. Credible intervals are %s.", TAU_LABEL, MU_LABEL, kind_txt),
               "Bayes factors use the Savage–Dickey ratio (posterior over prior density at the null) and are shown only when that prior is proper; BF₀₁ above 1 favors the null."),
  charts = charts,
  values = list(
    k = k, mu_mean = fit$mu_mean, mu_sd = fit$mu_sd, mu_median = fit$mu_median, mu_low = fit$mu_low, mu_high = fit$mu_high,
    mu_median_bt = bt(fit$mu_median), mu_low_bt = bt(fit$mu_low), mu_high_bt = bt(fit$mu_high),
    tau_median = fit$tau_median, tau_mode = fit$tau_mode, tau_low = fit$tau_low, tau_high = fit$tau_high,
    i2_median = fit$i2_median, i2_low = fit$i2_low, i2_high = fit$i2_high,
    pred_median = fit$pred_median, pred_low = fit$pred_low, pred_high = fit$pred_high,
    pred_median_bt = bt(fit$pred_median), pred_low_bt = bt(fit$pred_low), pred_high_bt = bt(fit$pred_high),
    p_mu_positive = fit$p_mu_positive, bf01_tau = fit$bf01_tau, bf01_mu = fit$bf01_mu,
    theta_mean = vapply(theta, function(t) t$mean, numeric(1)), theta_low = th_lo, theta_high = th_hi,
    measure = measure, measure_label = MEASURE_LABEL, effect_label = DISPLAY_LABEL, tau_prior_label = TAU_LABEL, mu_prior_label = MU_LABEL,
    interval_label = kind_txt, cred_level = conf
  )
))

Sources

  • Röver, C. (2020). Bayesian random-effects meta-analysis using the bayesmeta R package. Journal of Statistical Software, 93(6), 1–51.
  • Röver, C., & Friede, T. (2017). Discrete approximation of a mixture distribution via restricted divergence. Journal of Computational and Graphical Statistics, 26, 217–222.
  • Röver, C., Bender, R., Dias, S., Schmid, C. H., Schmidli, H., Sturtz, S., Weber, S., & Friede, T. (2021). On weakly informative prior distributions for the heterogeneity parameter in Bayesian random-effects meta-analysis. Research Synthesis Methods, 12, 448–474.
  • Gelman, A. (2006). Prior distributions for variance parameters in hierarchical models. Bayesian Analysis, 1, 515–534.
  • Friede, T., Röver, C., Wandel, S., & Neuenschwander, B. (2017). Meta-analysis of few small studies in orphan diseases. Research Synthesis Methods, 8, 79–91.
  • Higgins, J. P. T., & Thompson, S. G. (2002). Quantifying heterogeneity in a meta-analysis. Statistics in Medicine, 21, 1539–1558.

From the CodeSplash method registry · meta.bayes v1.0.2.