Several effects from the same study
Treating many effects from one study as independent understates uncertainty. Use a three-level model with cluster-robust inference instead.
What runs in CodeSplash
- Multilevel meta-analysis (several effects per study) Verified in Python and R
You will be able to
- Say why effects from one study are not independent
- Read a three-level model's split of variance within and between clusters
- Explain what cluster-robust inference adds
Read first
Fifty-six effects, eleven districts
ReadOne school district runs several experiments. Those results share teachers, students and local conditions, so they are not independent.
The Konstantopoulos data has 56 effects from 11 districts. An ordinary meta-analysis would act as if it had 56 independent studies.
A multilevel meta-analysisMultilevel meta-analysisA meta-analysis for several effects per study, separating differences between studies from differences within them. splits the variation into three levels:
- Sampling error, known from each effect's SE.
- True differences between effects within a district.
- True differences between districts.
What does ignoring clustering do?
PredictPredict first
You pool all the effects as if independent. Compared with the honest analysis, what happens to the interval around the average?
Reveal
Too narrow. You are counting correlated results as independent information, much as with repeated measures treated as separate people. Compare the clustered-independence explorable below.
See the design effect
ExploreRaise the correlation within clusters and watch the false positive rate of the naive analysis climb. The same thing happens here.
BExplorable · When observations come in clusters
What happens to a t test when students come in classrooms and you ignore it?
There is no true effect. How often does the naive t test reject?
Commit your prediction above to see the result
Make your prediction to see the result.
Read the card
Readeffect = 0.18, 95% CI [−0.00, 0.37], p = .054; σ²(between) = 0.07, σ²(within) = 0.03; k = 56 effects in m = 11 studies
- Pooled effect
- 0.1847
- p
- .054
- σ² between studies
- 0.0651
- σ² within studies
- 0.0327
- I² total (%)
- 95.187
Effect size
- Pooled effect 0.1847 95% CI [−0.0036, 0.3730]
Plots
View data
| effect | high | row | study | low | weight % |
|---|---|---|---|---|---|
| −0.1257 | 0.2273 | study | District 11 | −0.4786 | 6.762 |
| 0.0665 | 0.1902 | study | District 12 | −0.0571 | 9.243 |
| 0.3503 | 0.5103 | study | District 18 | 0.1903 | 8.537 |
| 0.4997 | 0.5742 | study | District 27 | 0.4252 | 9.507 |
| 0.0510 | 0.1282 | study | District 56 | −0.0261 | 9.502 |
| −0.0418 | 0.0190 | study | District 58 | −0.1026 | 10.328 |
| 0.8855 | 1.008 | study | District 71 | 0.7634 | 8.944 |
| −0.0288 | −0.0068 | study | District 86 | −0.0507 | 10.320 |
| 0.2505 | 0.3336 | study | District 91 | 0.1673 | 9.883 |
| 0.0150 | 0.1678 | study | District 108 | −0.1378 | 9.203 |
| 0.1619 | 0.4298 | study | District 644 | −0.1059 | 7.771 |
| 0.1847 | 0.3730 | summary | Pooled (three-level) | −0.0036 | 100 |
Assumptions
- Enough studies — 11 studies; cluster-robust standard errors tend to be too small with fewer than about 20 studies.
- Sampling errors within a study — Treated as independent in the model. Cluster-robust inference protects the standard errors if they are correlated.
- Each level earns its place — Between studies: LR = 17.77, p < .001; within studies: LR = 48.52, p < .001.
Where the variation sits
| Level | Variance | Share % | LR | p |
|---|---|---|---|---|
| Level 3: between studies | 0.0651 | 63.325 | 17.774 | 1.244e-5 |
| Level 2: between effects within a study | 0.0327 | 31.862 | 48.516 | 1.638e-12 |
| Level 1: sampling error (typical) | 0.0049 | 4.813 | — | — |
Coefficients (effect scale, 95% CI)
| Term | Estimate | SE | t | p | CI low | CI high |
|---|---|---|---|---|---|---|
| intercept | 0.1847 | 0.0845 | 2.186 | 0.0537 | −0.0036 | 0.3730 |
- 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.537, 0.907].
The exact R script · R 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 1094e16fc378caca
# 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 = "robust", 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
))
effect = 0.18, 95% CI [−0.00, 0.37], p = .054; σ²(between) = 0.07, σ²(within) = 0.03; k = 56 effects in m = 11 studies
- Pooled effect
- 0.1847
- p
- .054
- σ² between studies
- 0.0651
- σ² within studies
- 0.0327
- I² total (%)
- 95.187
Effect size
- Pooled effect 0.1847 95% CI [−0.0036, 0.3730]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough studies — 11 studies; cluster-robust standard errors tend to be too small with fewer than about 20 studies.
- Sampling errors within a study — Treated as independent in the model. Cluster-robust inference protects the standard errors if they are correlated.
- Each level earns its place — Between studies: LR = 17.77, p < .001; within studies: LR = 48.52, p < .001.
Where the variation sits
| Level | Variance | Share % | LR | p |
|---|---|---|---|---|
| Level 3: between studies | 0.0651 | 63.325 | 17.774 | 1.244e-5 |
| Level 2: between effects within a study | 0.0327 | 31.862 | 48.516 | 1.638e-12 |
| Level 1: sampling error (typical) | 0.0049 | 4.813 | — | — |
Coefficients (effect scale, 95% CI)
| Term | Estimate | SE | t | p | CI low | CI high |
|---|---|---|---|---|---|---|
| intercept | 0.1847 | 0.0845 | 2.186 | 0.0537 | −0.0036 | 0.3730 |
- 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.537, 0.907].
The exact Python script · Python 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 1094e16fc378caca
# 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="robust", 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,
})
The average effect is 0.185. Variance splits into:
- Between districts: 63% of the total.
- Within districts: 32%.
Likelihood-ratio tests ask whether each level is needed: p < .001 and p < .001. Both are.
Model-based or robust?
ReadSame data, same estimate, different question about the standard error:
- Model-based Wald z: p = .029. It trusts the three-level model's structure.
- Cluster-robust t (CR1): p = .054 on 10 df. It uses the variation between districts directly and survives some misspecification.
Note the cost: effective df comes from the number of clusters, not effects. CodeSplash uses CR1 by default; the CR2 small-sample correction isn't available yet, so treat results with few clusters cautiously.
Which would you report?
ReflectOne of these p-values is below 0.05 and the other is not. Before you look at either, which inference would you have pre-specified, and why?
Notice how close the two estimates of uncertainty are. A crossing of 0.05 here shows how little that threshold can carry.
Check your understanding
CheckpointCheck yourself
This intercept-only cluster-robust analysis has 56 effects from 11 districts. How many degrees of freedom does the t test use?
Show the answer
Answer: 10
Clusters minus coefficients: . The count of clusters drives the inference, not the count of effects.
Check yourself
Why does a three-level model need the second level at all?
Show the answer
Answer: a
Level 2 captures real variation between effects in the same cluster: different outcomes, subgroups or time points.
Check yourself
You have 120 effects from 6 studies. What is the main worry?
Show the answer
Answer: b
Precision and df come largely from the number of independent clusters.
Do it in CodeSplash
In the appIn the Meta-analysis studio, start from the template Several effects per study. Choose a cluster column (the study or district) and an effect label for each row.
Recap
Recap- Effects from one study are correlated. Treating them as independent makes intervals too narrow.
- A three-level model separates sampling error, within-cluster and between-cluster variation.
- Cluster-robust inference depends on the number of clusters, so report that number.
Concepts in this lesson