Skip to content

BMeta-analysis · meta.multilevel

Multilevel meta-analysis (several effects per study)

What is the average effect when studies report several effects each, and where does the variation sit?

Three-level random-effects meta-analysis for dependent effect sizes: sampling error (level 1), differences between effects within a study (level 2) and differences between studies (level 3), by REML or ML, with optional moderators, cluster-robust or model-based inference, I² by level and likelihood-ratio tests of whether each level earns its place.

Verified in Python and R Python and R agree to 10 decimals Also called three-level meta-analysis, dependent effect sizes, robust variance estimation…

A real result

Example “Konstantopoulos reml”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Multilevel meta-analysis of 56 effects in 11 studies (three-level, REML, Wald z)Recorded · Python and R agreeRecorded 2026-11-17 · 44 values compared
R

effect = 0.18, 95% CI [0.02, 0.35], p = .029; σ²(between) = 0.07, σ²(within) = 0.03; k = 56 effects in m = 11 studies

Pooled effect
0.1847
p
.029
σ² between studies
0.0651
σ² within studies
0.0327
I² total (%)
95.187

Effect size

  • Pooled effect 0.1847 95% CI [0.0190, 0.3504]

Plots

Studies (mean of each study's effects) and the pooled estimateHow do the studies' effects compare, and what is the pooled effect and its spread?
View data
effecthighrowstudylowweight %
−0.12570.2273studyDistrict 11−0.47866.762
0.06650.1902studyDistrict 12−0.05719.243
0.35030.5103studyDistrict 180.19038.537
0.49970.5742studyDistrict 270.42529.507
0.05100.1282studyDistrict 56−0.02619.502
−0.04180.0190studyDistrict 58−0.102610.328
0.88551.008studyDistrict 710.76348.944
−0.0288−0.0068studyDistrict 86−0.050710.320
0.25050.3336studyDistrict 910.16739.883
0.01500.1678studyDistrict 108−0.13789.203
0.16190.4298studyDistrict 644−0.10597.771
0.18470.3504summaryPooled (three-level)0.0190100

Assumptions

  • Enough studies — 11 studies.
  • Sampling errors within a study — Treated as independent in the model. Model-based inference relies on this; consider cluster-robust inference.
  • Each level earns its place — Between studies: LR = 17.77, p < .001; within studies: LR = 48.52, p < .001.

Where the variation sits

LevelVarianceShare %LRp
Level 3: between studies0.065163.32517.7741.244e-5
Level 2: between effects within a study0.032731.86248.5161.638e-12
Level 1: sampling error (typical)0.00494.813——

Coefficients (effect scale, 95% CI)

TermEstimateSEzpCI lowCI high
intercept0.18470.08462.1850.02890.01900.3504
  • Likelihood-ratio p-values use the 50:50 mixture of χ²₀ and χ²₁ for a variance tested at its boundary.
  • Prediction interval for a new effect's true value: [-0.45, 0.82].
Python

effect = 0.18, 95% CI [0.02, 0.35], p = .029; σ²(between) = 0.07, σ²(within) = 0.03; k = 56 effects in m = 11 studies

Pooled effect
0.1847
p
.029
σ² between studies
0.0651
σ² within studies
0.0327
I² total (%)
95.187

Effect size

  • Pooled effect 0.1847 95% CI [0.0190, 0.3504]

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

Assumptions

  • Enough studies — 11 studies.
  • Sampling errors within a study — Treated as independent in the model. Model-based inference relies on this; consider cluster-robust inference.
  • Each level earns its place — Between studies: LR = 17.77, p < .001; within studies: LR = 48.52, p < .001.

Where the variation sits

LevelVarianceShare %LRp
Level 3: between studies0.065163.32517.7741.244e-5
Level 2: between effects within a study0.032731.86248.5161.638e-12
Level 1: sampling error (typical)0.00494.813——

Coefficients (effect scale, 95% CI)

TermEstimateSEzpCI lowCI high
intercept0.18470.08462.1850.02890.01900.3504
  • Likelihood-ratio p-values use the 50:50 mixture of χ²₀ and χ²₁ for a variance tested at its boundary.
  • Prediction interval for a new effect's true value: [-0.45, 0.82].

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

  • Konstantopoulos remlm1_multilevel · cluster: district · effect: effect · se: se · study: effect_id
  • Konstantopoulos robustm1_multilevel · cluster: district · effect: effect · se: se · study: effect_id
  • Assink mlm1_assink · cluster: study · effect: effect · se: se · study: effect_id
  • Assink moderatorsm1_assink · cluster: study · effect: effect · moderators: deltype, year · se: se · study: effect_id
  • Assink moderators zm1_assink · cluster: study · effect: effect · moderators: pubstatus · se: se · study: effect_id
  • Degenerate n1m1_multilevel · cluster: district · effect: effect · se: se · study: effect_id
  • Degenerate n3m1_multilevel · cluster: district · effect: effect · se: se · study: effect_id

What you need

Study (cluster)categorical · 1 column
The study each effect belongs to; effects from one study share a level 3 random effect.
Effect labels (optional)categorical · 0–1 column
Names individual effects in warnings; the forest plot shows one row per study.
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.
Moderators (optional)numeric / categorical / boolean · 0–5 columns
Characteristics of effects or studies that may explain differences; categories use the first level as the reference.

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

Variance estimatordefault REML

How the two variance components are estimated; REML corrects for estimating the fixed effects.

  • Restricted maximum likelihood (REML)(default) — Estimates the variance components by restricted likelihood; the usual choice.
  • Maximum likelihood — Needed to compare models with different moderators by likelihood ratio.
Inferencedefault robust

Cluster-robust stays valid when effects in a study have correlated sampling errors, which this model does not include.

  • Cluster-robust t (CR1, m − p df)(default) — Robust variance estimation by study; needs roughly 20 or more studies to be reliable.
  • Model-based Wald z — Trusts the three-level model, including independent sampling errors within a study.

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 effectsNot checked from data: state why it holds

    Effects estimate the same kind of quantity, so pooling them is worth doing.

  • Sampling errors within a study

    The model treats sampling errors within a study as independent; cluster-robust inference protects against correlated ones.

  • Enough studies

    Cluster-robust inference is unreliable with few studies (below about 20) and variance components are imprecise below about 10.

  • Each level earns its place

    Likelihood-ratio tests show whether within-study and between-study variation are distinguishable from zero.

What it reports

  • Tests: Pooled effect differs from zero
  • Tests: Variation between studies (level 3)
  • Tests: Variation within studies (level 2)
n_effects
How many independent units the analysis used; it sets precision and power.
m
How many independent groups the result rests on, such as the studies in a multilevel meta-analysis.
n_coef
How many coefficients the model estimated, counting the intercept.
est
The average effect across studies from a meta-analysis, weighted by each study's precision.
se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
stat
A single number that summarizes how far your data are from what H₀ predicts.
p
How surprising your data would be if the null hypothesis were true, as a probability.
ci_low
A range of effect values compatible with your data at the chosen confidence level.
ci_high
A range of effect values compatible with your data at the chosen confidence level.
est_bt
The average effect across studies from a meta-analysis, weighted by each study's precision.
ci_low_bt
A range of effect values compatible with your data at the chosen confidence level.
ci_high_bt
A range of effect values compatible with your data at the chosen confidence level.
df
How much independent information is left to estimate variability after fitting the model.
s2_between
A meta-analysis for several effects per study, separating differences between studies from differences within them.
s2_within
A meta-analysis for several effects per study, separating differences between studies from differences within them.
typical_v
A meta-analysis for several effects per study, separating differences between studies from differences within them.
i2_between
The share of the variation in study estimates that comes from real differences between studies rather than sampling error.
i2_within
The share of the variation in study estimates that comes from real differences between studies rather than sampling error.
i2_total
The share of the variation in study estimates that comes from real differences between studies rather than sampling error.
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.
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.
lr_between
A meta-analysis for several effects per study, separating differences between studies from differences within them.
lr_between_p
How surprising your data would be if the null hypothesis were true, as a probability.
lr_within
A meta-analysis for several effects per study, separating differences between studies from differences within them.
lr_within_p
How surprising your data would be if the null hypothesis were true, as a probability.
pi_low
Where the true effect of a new, comparable study would be expected to fall — wider than the CI of the mean whenever τ² > 0.
pi_high
Where the true effect of a new, comparable study would be expected to fall — wider than the CI of the mean whenever τ² > 0.
pi_low_bt
Where the true effect of a new, comparable study would be expected to fall — wider than the CI of the mean whenever τ² > 0.
pi_high_bt
Where the true effect of a new, comparable study would be expected to fall — wider than the CI of the mean whenever τ² > 0.
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.
model_label
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
k_left_out
The average effect across studies from a meta-analysis, weighted by each study's precision.
n_clusters
How many independent units the analysis used; it sets precision and power.

Per group, level or term: b[<term>], se[<term>], p[<term>], ci_low[<term>], ci_high[<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

  • The variance components are the codesplash Fisher-scoring twin with the same step rule in both engines; metafor::rma.mv uses a general optimizer, so its components agree with these to about 4 decimals.
Python

The exact script CodeSplash ran for example “Konstantopoulos reml” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Multilevel meta-analysis (several effects per study)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.multilevel 1.0.1 · spec af55c24e73b33237
# Dataset: m1_multilevel (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_multilevel.parquet", columns=["district", "effect_id", "effect", "se"])
n_input = len(df)
df["district"] = pd.Categorical(df["district"], categories=sorted(df["district"].dropna().unique()))
df["effect_id"] = pd.Categorical(df["effect_id"], categories=sorted(df["effect_id"].dropna().unique()))
df = df.dropna(subset=["district", "effect_id", "effect", "se"])  # listwise deletion over the analysis columns
df["district"] = df["district"].cat.remove_unused_categories()
df["effect_id"] = df["effect_id"].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, ["district", "effect_id", "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["effect_id"].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)

# %% Studies and the design matrix (categories: indicator per level against the first, stored level order)
cluster = df["district"].astype(str).to_numpy()[idx]
n_clusters = len(set(cluster))
if n_clusters < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column="district", min=2, k=n_clusters)  # between-study variance needs two studies
mods = []
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]

# %% Fit
conf = 0.95
fit = meta.multilevel(y, v, cluster, X, method="REML", inference="z", level=conf)
m_studies, p_coef = fit["m"], fit["p"]
robust = fit["inference"] == "robust"
model_label = f"three-level, {fit['method']}, " + ("cluster-robust t" if robust else "Wald z")
stat_name = "t" if robust else "z"
est, se, stat, p_val, ci_low, ci_high = (float(fit[key][0]) for key in ("beta", "se", "stat", "pval", "ci_low", "ci_high"))
intercept_only = p_coef == 1
# A new effect's true value, from the model's two variance components.
pi_half = fit["crit"] * math.sqrt(se ** 2 + fit["s2_between"] + fit["s2_within"])
pi_low, pi_high = (est - pi_half, est + pi_half) if intercept_only else (float("nan"), float("nan"))
to_bt = lambda t: float(bt(t)) if not math.isnan(t) else t  # noqa: E731
disp = DISPLAY_LABEL

# %% Assumptions
few_robust = robust and m_studies < 20
assumptions = [
    {"key": "k_clusters", "label": "Enough studies", "status": "warn" if m_studies < 10 or few_robust else "pass",
     "detail": f"{m_studies} studies" + ("; cluster-robust standard errors tend to be too small with fewer than about 20 studies." if few_robust else ".")},
    {"key": "correlated_errors", "label": "Sampling errors within a study", "status": "info",
     "detail": "Treated as independent in the model." + (" Cluster-robust inference protects the standard errors if they are correlated." if robust else " Model-based inference relies on this; consider cluster-robust inference.")},
    {"key": "level_needed", "label": "Each level earns its place", "status": "info",
     "detail": f"Between studies: LR = {fit['lr_between']:.2f}, {cs.fmt_p(fit['lr_between_p'])}; within studies: LR = {fit['lr_within']:.2f}, {cs.fmt_p(fit['lr_within_p'])}."},
]

# %% 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])} for j in range(p_coef)]
share = lambda x: 100 * x / (fit["s2_between"] + fit["s2_within"] + fit["typical_v"])  # noqa: E731
level_rows = [
    {"level": "Level 3: between studies", "variance": fit["s2_between"], "share": share(fit["s2_between"]), "lr": fit["lr_between"], "p": fit["lr_between_p"]},
    {"level": "Level 2: between effects within a study", "variance": fit["s2_within"], "share": share(fit["s2_within"]), "lr": fit["lr_within"], "p": fit["lr_within_p"]},
    {"level": "Level 1: sampling error (typical)", "variance": fit["typical_v"], "share": share(fit["typical_v"]), "lr": None, "p": None},
]
values = {
    "n_effects": fit["n"], "m": m_studies, "n_clusters": m_studies, "n_coef": p_coef, "k_left_out": len(left_out),
    "est": est, "se": se, "stat": stat, "p": p_val, "ci_low": ci_low, "ci_high": ci_high,
    "est_bt": to_bt(est), "ci_low_bt": to_bt(ci_low), "ci_high_bt": to_bt(ci_high), "df": fit["df"] if robust else float("nan"),
    "s2_between": fit["s2_between"], "s2_within": fit["s2_within"], "typical_v": fit["typical_v"],
    "i2_between": fit["i2_between"], "i2_within": fit["i2_within"], "i2_total": fit["i2_total"],
    "qe": fit["qe"], "qe_df": float(fit["qe_df"]), "qe_p": fit["qe_p"], "qm": fit["qm"], "qm_df": float(fit["qm_df"]), "qm_p": fit["qm_p"],
    "lr_between": fit["lr_between"], "lr_between_p": fit["lr_between_p"], "lr_within": fit["lr_within"], "lr_within_p": fit["lr_within_p"],
    "pi_low": pi_low, "pi_high": pi_high, "pi_low_bt": to_bt(pi_low), "pi_high_bt": to_bt(pi_high),
    "measure": measure, "measure_label": MEASURE_LABEL, "effect_label": disp, "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])

charts = []
if intercept_only:
    # One row per study: its effects' precision-weighted mean, with the model's share of the weight.
    zc = float(fit["crit"]) if not robust else float(meta.stats.norm.ppf(1 - (1 - conf) / 2))
    names, ests, los, his = [], [], [], []
    for g in fit["groups"]:
        wg = 1 / v[g]
        mean_g = float(np.sum(wg * y[g]) / np.sum(wg))
        half = zc / math.sqrt(float(np.sum(wg)))
        names.append(str(cluster[g[0]]))
        ests.append(float(bt(mean_g))); los.append(float(bt(mean_g - half))); his.append(float(bt(mean_g + half)))
    charts.append(cs.chart("forest", "forest-meta", "Studies (mean of each study's effects) and the pooled estimate",
                           {"label": cs.col("study", names + ["Pooled (three-level)"]), "estimate": cs.col(disp, ests + [to_bt(est)]),
                            "low": cs.col("low", los + [to_bt(ci_low)]), "high": cs.col("high", his + [to_bt(ci_high)]),
                            "weight": cs.col("weight %", [float(t) for t in fit["weights"]] + [100.0]),
                            "kind": cs.col("row", ["study"] * m_studies + ["summary"])},
                           controls={"reference": 1 if RATIO else 0, "log": RATIO, "piLow": to_bt(pi_low), "piHigh": to_bt(pi_high)}))
cs.publish({
    "method": "meta.multilevel",
    "methodVersion": "1.0.1",
    "title": f"Multilevel meta-analysis of {fit['n']} effects in {m_studies} studies ({model_label})",
    "engine": cs.engine_info("numpy", "scipy"),
    "n": fit["n"],
    "summary": f"Pooled {disp} {bt(est):.3g}, {conf:.0%} CI [{bt(ci_low):.3g}, {bt(ci_high):.3g}], {cs.fmt_p(p_val)}; I² between studies {fit['i2_between']:.1f}%, within studies {fit['i2_within']:.1f}%.",
    "apa": f"{disp} = {cs.fmt_num(to_bt(est))}, {conf:.0%} CI [{cs.fmt_num(to_bt(ci_low))}, {cs.fmt_num(to_bt(ci_high))}], {cs.fmt_p(p_val)}; σ²(between) = {cs.fmt_num(fit['s2_between'])}, σ²(within) = {cs.fmt_num(fit['s2_within'])}; k = {fit['n']} effects in m = {m_studies} studies",
    "statistics": [
        {"key": "est_bt", "label": "Pooled " + disp, "value": to_bt(est)}, {"key": "p", "label": "p", "value": p_val, "format": "p"},
        {"key": "s2_between", "label": "σ² between studies", "value": fit["s2_between"]}, {"key": "s2_within", "label": "σ² within studies", "value": fit["s2_within"]},
        {"key": "i2_total", "label": "I² total (%)", "value": fit["i2_total"]},
    ],
    "tables": [
        {"key": "levels", "title": "Where the variation sits",
         "columns": [{"key": "level", "label": "Level", "type": "string"}, {"key": "variance", "label": "Variance", "type": "number"},
                     {"key": "share", "label": "Share %", "type": "number"}, {"key": "lr", "label": "LR", "type": "number"}, {"key": "p", "label": "p", "type": "number"}],
         "rows": level_rows},
        {"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"}],
         "rows": coef_rows},
    ],
    "effectSizes": [{"key": "est_bt", "label": "Pooled " + disp, "value": to_bt(est), "ciLow": to_bt(ci_low), "ciHigh": to_bt(ci_high), "ciLevel": conf, "method": model_label}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["Likelihood-ratio p-values use the 50:50 mixture of χ²₀ and χ²₁ for a variance tested at its boundary."] + ([f"Prediction interval for a new effect's true value: [{bt(pi_low):.3g}, {bt(pi_high):.3g}]."] if intercept_only else []),
    "charts": charts,
    "values": values,
})
R

The exact script CodeSplash ran for example “Konstantopoulos reml” · R version 4.5.1 (2025-06-13)

# Multilevel meta-analysis (several effects per study)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method meta.multilevel 1.0.1 · spec af55c24e73b33237
# Dataset: m1_multilevel (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_multilevel.parquet", col_select = c("district", "effect_id", "effect", "se")))
n_input <- nrow(df)
df[["district"]] <- factor(df[["district"]], levels = sort(unique(df[["district"]]), method = "radix"))
df[["effect_id"]] <- factor(df[["effect_id"]], levels = sort(unique(df[["effect_id"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("district", "effect_id", "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("district", "effect_id", "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[["effect_id"]])
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

# %% Studies and the design matrix (categories: indicator per level against the first, stored level order)
cluster <- as.character(df[["district"]])[idx]
n_clusters <- length(unique(cluster))
if (n_clusters < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = "district", min = 2, k = n_clusters)  # between-study variance needs two studies
mods <- c()
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]

# %% Fit
conf <- 0.95
fit <- cs_meta_multilevel(y, v, cluster, X, method = "REML", inference = "z", level = conf)
m_studies <- fit$m; p_coef <- fit$p
robust <- fit$inference == "robust"
model_label <- paste0("three-level, ", fit$method, ", ", if (robust) "cluster-robust t" else "Wald z")
stat_name <- if (robust) "t" else "z"
est <- fit$beta[1]; se <- fit$se[1]; stat <- fit$stat[1]; p_val <- fit$pval[1]; ci_low <- fit$ci_low[1]; ci_high <- fit$ci_high[1]
intercept_only <- p_coef == 1
# A new effect's true value, from the model's two variance components.
pi_half <- fit$crit * sqrt(se^2 + fit$s2_between + fit$s2_within)
pi_low <- if (intercept_only) est - pi_half else NaN
pi_high <- if (intercept_only) est + pi_half else NaN
to_bt <- function(t) if (is.nan(t)) t else bt(t)
disp <- DISPLAY_LABEL

# %% Assumptions
few_robust <- robust && m_studies < 20
assumptions <- list(
  list(key = "k_clusters", label = "Enough studies", status = if (m_studies < 10 || few_robust) "warn" else "pass",
       detail = paste0(sprintf("%d studies", m_studies), if (few_robust) "; cluster-robust standard errors tend to be too small with fewer than about 20 studies." else ".")),
  list(key = "correlated_errors", label = "Sampling errors within a study", status = "info",
       detail = paste0("Treated as independent in the model.", if (robust) " Cluster-robust inference protects the standard errors if they are correlated." else " Model-based inference relies on this; consider cluster-robust inference.")),
  list(key = "level_needed", label = "Each level earns its place", status = "info",
       detail = sprintf("Between studies: LR = %.2f, %s; within studies: LR = %.2f, %s.", fit$lr_between, cs_fmt_p(fit$lr_between_p), fit$lr_within, cs_fmt_p(fit$lr_within_p)))
)

# %% 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]))
share <- function(x) 100 * x / (fit$s2_between + fit$s2_within + fit$typical_v)
level_rows <- list(
  list(level = "Level 3: between studies", variance = fit$s2_between, share = share(fit$s2_between), lr = fit$lr_between, p = fit$lr_between_p),
  list(level = "Level 2: between effects within a study", variance = fit$s2_within, share = share(fit$s2_within), lr = fit$lr_within, p = fit$lr_within_p),
  list(level = "Level 1: sampling error (typical)", variance = fit$typical_v, share = share(fit$typical_v), lr = NULL, p = NULL)
)
values <- list(
  n_effects = fit$n, m = m_studies, n_clusters = m_studies, n_coef = p_coef, k_left_out = length(left_out),
  est = est, se = se, stat = stat, p = p_val, ci_low = ci_low, ci_high = ci_high,
  est_bt = to_bt(est), ci_low_bt = to_bt(ci_low), ci_high_bt = to_bt(ci_high), df = if (robust) fit$df else NaN,
  s2_between = fit$s2_between, s2_within = fit$s2_within, typical_v = fit$typical_v,
  i2_between = fit$i2_between, i2_within = fit$i2_within, i2_total = fit$i2_total,
  qe = fit$qe, qe_df = fit$qe_df, qe_p = fit$qe_p, qm = fit$qm, qm_df = fit$qm_df, qm_p = fit$qm_p,
  lr_between = fit$lr_between, lr_between_p = fit$lr_between_p, lr_within = fit$lr_within, lr_within_p = fit$lr_within_p,
  pi_low = pi_low, pi_high = pi_high, pi_low_bt = to_bt(pi_low), pi_high_bt = to_bt(pi_high),
  measure = measure, measure_label = MEASURE_LABEL, effect_label = disp, 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]
}

charts <- list()
if (intercept_only) {
  # One row per study: its effects' precision-weighted mean, with the model's share of the weight.
  zc <- if (robust) qnorm(1 - (1 - conf) / 2) else fit$crit
  names_g <- character(0); ests <- numeric(0); los <- numeric(0); his <- numeric(0)
  for (g in fit$groups) {
    wg <- 1 / v[g]
    mean_g <- sum(wg * y[g]) / sum(wg)
    half <- zc / sqrt(sum(wg))
    names_g <- c(names_g, cluster[g[1]])
    ests <- c(ests, bt(mean_g)); los <- c(los, bt(mean_g - half)); his <- c(his, bt(mean_g + half))
  }
  charts[[1]] <- cs_chart("forest", "forest-meta", "Studies (mean of each study's effects) and the pooled estimate",
                          list(label = cs_col("study", c(names_g, "Pooled (three-level)")), estimate = cs_col(disp, c(ests, to_bt(est))),
                               low = cs_col("low", c(los, to_bt(ci_low))), high = cs_col("high", c(his, to_bt(ci_high))),
                               weight = cs_col("weight %", c(fit$weights, 100)),
                               kind = cs_col("row", c(rep("study", m_studies), "summary"))),
                          controls = list(reference = if (RATIO) 1 else 0, log = RATIO, piLow = to_bt(pi_low), piHigh = to_bt(pi_high)))
}
cs_publish(list(
  method = "meta.multilevel",
  methodVersion = "1.0.1",
  title = sprintf("Multilevel meta-analysis of %d effects in %d studies (%s)", as.integer(fit$n), as.integer(m_studies), model_label),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = fit$n,
  summary = sprintf("Pooled %s %.3g, %.0f%% CI [%.3g, %.3g], %s; I² between studies %.1f%%, within studies %.1f%%.", disp, to_bt(est), conf * 100, to_bt(ci_low), to_bt(ci_high), cs_fmt_p(p_val), fit$i2_between, fit$i2_within),
  apa = sprintf("%s = %s, %.0f%% CI [%s, %s], %s; σ²(between) = %s, σ²(within) = %s; k = %d effects in m = %d studies", disp, cs_fmt_num(to_bt(est)), conf * 100, cs_fmt_num(to_bt(ci_low)), cs_fmt_num(to_bt(ci_high)), cs_fmt_p(p_val), cs_fmt_num(fit$s2_between), cs_fmt_num(fit$s2_within), as.integer(fit$n), as.integer(m_studies)),
  statistics = list(
    list(key = "est_bt", label = paste("Pooled", disp), value = to_bt(est)), list(key = "p", label = "p", value = p_val, format = "p"),
    list(key = "s2_between", label = "σ² between studies", value = fit$s2_between), list(key = "s2_within", label = "σ² within studies", value = fit$s2_within),
    list(key = "i2_total", label = "I² total (%)", value = fit$i2_total)
  ),
  tables = list(
    list(key = "levels", title = "Where the variation sits",
         columns = list(list(key = "level", label = "Level", type = "string"), list(key = "variance", label = "Variance", type = "number"),
                        list(key = "share", label = "Share %", type = "number"), list(key = "lr", label = "LR", type = "number"), list(key = "p", label = "p", type = "number")),
         rows = level_rows),
    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")),
         rows = coef_rows)
  ),
  effectSizes = list(list(key = "est_bt", label = paste("Pooled", disp), value = to_bt(est), ciLow = to_bt(ci_low), ciHigh = to_bt(ci_high), ciLevel = conf, method = model_label)),
  assumptions = assumptions,
  warnings = warnings,
  notes = c(list("Likelihood-ratio p-values use the 50:50 mixture of χ²₀ and χ²₁ for a variance tested at its boundary."),
            if (intercept_only) list(sprintf("Prediction interval for a new effect's true value: [%.3g, %.3g].", to_bt(pi_low), to_bt(pi_high))) else list()),
  charts = charts,
  values = values
))

Sources

  • Konstantopoulos, S. (2011). Fixed effects and variance components estimation in three-level meta-analysis. Research Synthesis Methods, 2, 61–76.
  • Van den Noortgate, W., López-López, J. A., Marín-Martínez, F., & Sánchez-Meca, J. (2013). Three-level meta-analysis of dependent effect sizes. Behavior Research Methods, 45, 576–594.
  • Hedges, L. V., Tipton, E., & Johnson, M. C. (2010). Robust variance estimation in meta-regression with dependent effect size estimates. Research Synthesis Methods, 1, 39–65.
  • Cheung, M. W.-L. (2014). Modeling dependent effect sizes with three-level meta-analyses. Psychological Methods, 19, 211–229.

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