BBayesian · bayes.anova
Bayesian ANOVA (model comparison)
Which factors (and interaction) do the data support, and by how much?
Default Bayes factors for one or two crossed between-subjects factors (Rouder, Morey, Speckman & Province 2012): every model is compared with the intercept-only model, the models are ranked by posterior probability, and each term gets an inclusion Bayes factor averaged over the models. Effects have g-priors of width r in an orthonormal parameterization; the integrals are computed numerically (no Monte Carlo error).
A real result
Example “Guide one way”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
BF = 60.43 for group vs the intercept-only model (r = 0.5)
- BF (group vs null)
- 60.429
- P(best model | data)
- 0.9837
- Inclusion BF: group
- 60.429
Plots
View data
| BF | model | posterior |
|---|---|---|
| 60.429 | group | 0.9837 |
Assumptions
- Normal residuals — Shapiro–Wilk on residuals from the cell means: W = 0.984, p = .605.
- Equal variances — Brown–Forsythe across 3 cells: F = 0.01, p = .994.
- Independent observations — Between-subjects factors only: each row a separate subject.
Models (against the intercept-only model)
| Model | BF | log BF | P(model | data) | Error % |
|---|---|---|---|---|
| Intercept only | 1 | 0 | 0.0163 | 0 |
| group | 60.429 | 4.101 | 0.9837 | 3.780e-7 |
Inclusion Bayes factors
| Term | BF (inclusion) |
|---|---|
| group | 60.429 |
Cell means
| group | n | Mean | SD |
|---|---|---|---|
| A | 20 | −0.3935 | 0.9628 |
| B | 20 | 0.7107 | 0.9280 |
| C | 20 | 0.5523 | 0.8232 |
- Each term has its own g ~ inverse-gamma(½, r²/2), r = 0.5; effects use orthonormal (Helmert) contrasts; flat intercept, Jeffreys prior on σ².
- Inclusion Bayes factors compare all models with a term against all models without it (equal prior model probabilities, null included).
- Bayes factors are relative evidence, not p-values; they are not entered in the multiple-testing ledger.
BF = 60.43 for group vs the intercept-only model (r = 0.5)
- BF (group vs null)
- 60.429
- P(best model | data)
- 0.9837
- Inclusion BF: group
- 60.429
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normal residuals — Shapiro–Wilk on residuals from the cell means: W = 0.984, p = .605.
- Equal variances — Brown–Forsythe across 3 cells: F = 0.01, p = .994.
- Independent observations — Between-subjects factors only: each row a separate subject.
Models (against the intercept-only model)
| Model | BF | log BF | P(model | data) | Error % |
|---|---|---|---|---|
| Intercept only | 1 | 0 | 0.0163 | 0 |
| group | 60.429 | 4.101 | 0.9837 | 3.780e-7 |
Inclusion Bayes factors
| Term | BF (inclusion) |
|---|---|
| group | 60.429 |
Cell means
| group | n | Mean | SD |
|---|---|---|---|
| A | 20 | −0.3935 | 0.9628 |
| B | 20 | 0.7107 | 0.9280 |
| C | 20 | 0.5523 | 0.8232 |
- Each term has its own g ~ inverse-gamma(½, r²/2), r = 0.5; effects use orthonormal (Helmert) contrasts; flat intercept, Jeffreys prior on σ².
- Inclusion Bayes factors compare all models with a term against all models without it (equal prior model probabilities, null included).
- Bayes factors are relative evidence, not p-values; they are not entered in the multiple-testing ledger.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Guide one waya_hetero3 · factors: group · outcome: value
- Plantgrowth ultrawideplantgrowth · factors: group · outcome: weight
- Warpbreaks two waywarpbreaks · factors: wool, tension · outcome: breaks
- Degenerate constanta_hetero3 · factors: group · outcome: value
- Degenerate single levela_hetero3 · factors: group · outcome: value
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- More than two independent groups: one-way ANOVA, Kruskal–Wallis · Statistics Guide · B — Compare groups
- Factorial designs, covariates, multivariate (ANCOVA, MANOVA) · Statistics Guide · B — Compare groups
What you need
- Outcomenumeric · 1 column
- The numeric outcome.
- Factorscategorical / boolean · 1–2 columns · 2–30 levels
- One factor, or two crossed between-subjects factors (their interaction is included in the model set).
Choices you make
hypothesis
- Prior width on effectsdefault medium
Scale of the g-prior on standardized effects (g ~ inverse-gamma(½, r²/2)); one value for every term.
- Medium (r = ½)(default) — BayesFactor's default for fixed effects.
- Wide (r = √2/2) — Larger effects expected.
- Ultrawide (r = 1) — Very large effects expected; favors simpler models more.
- Custom — Any positive scale r.
- Prior scale rdefault 0.5
Scale of the g-prior on standardized effects.
- Models compareddefault withmain
The set of models the inclusion Bayes factors average over.
- Interaction only with its main effects(default) — a, b, a + b, a + b + a × b (principle of marginality; BayesFactor's default).
- Every combination — All seven models, including an interaction without its main effects.
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.
Normal residuals
Shapiro–Wilk on residuals from the cell means.
Equal variances
Brown–Forsythe across cells: the model has one residual variance.
- If violated → Welch's ANOVA (frequentist, one factor) — Allows unequal variances; the default Bayesian ANOVA has one residual variance. Changes the question: A p-value for equal means instead of Bayes factors over models.
Independent observations
Between-subjects factors only; repeated measures need a mixed model.
What it reports
- bf_best
- How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
- best_model
- The model with the largest Bayes factor against the intercept-only model, named by its terms joined with +.
- p_best
- How probable each model is after the data, given equal prior probabilities for the models compared.
- bf_full
- How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
- bf_incl_1
- The change from prior to posterior odds that a term belongs in the model, averaged over every model with and without it.
- bf_incl_2
- The change from prior to posterior odds that a term belongs in the model, averaged over every model with and without it.
- bf_incl_interaction
- The change from prior to posterior odds that a term belongs in the model, averaged over every model with and without it.
- p_null
- How probable each model is after the data, given equal prior probabilities for the models compared.
- n
- How many independent units the analysis used; it sets precision and power.
- k_models
- How many models were compared with the intercept-only model; the intercept-only model itself is not counted.
- r
- A number from −1 to 1 for how closely two variables move together; Pearson measures straight-line association.
- error_pct
- Estimated error of the numerical integration behind the Bayes factor, in percent of its value (ANOVA: the largest over models).
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- BayesFactor::anovaBF estimates multi-factor Bayes factors by importance sampling (typically ±1%); both engines here integrate the 2–3 g-parameters with the same nested adaptive Gauss–Kronrod rule (relative error ≈1e-8). One-factor Bayes factors agree with BayesFactor to 1e-9.
The exact script CodeSplash ran for example “Guide one way” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bayesian ANOVA (model comparison)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.anova 1.0.1 · spec 8b6feb244a98ff37
# Dataset: a_hetero3 (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import bayes as bf # default ANOVA Bayes factors (twin of R cs_bayes_anova)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/a_hetero3.parquet", columns=["value", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["A", "B", "C"]) # stored level order
df = df.dropna(subset=["value", "group"]) # listwise deletion over the analysis columns
df["group"] = df["group"].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, ["value", "group"]) # infinite values stop the run (registry/errors.yaml)
# %% Models
y = "value"
factor_cols = ["group"]
r = bf.prior_scale("anova", "medium", 0.5)
which = "withmain"
codes, nlev = [], []
for f in factor_cols:
cats = list(df[f].cat.categories)
if len(cats) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=f, min=2, k=len(cats))
codes.append(df[f].cat.codes.to_numpy())
nlev.append(len(cats))
yv = df[y].to_numpy(dtype=float)
if len(np.unique(yv)) < 2: # no variation: every Bayes factor is 0/0
cs.cs_error("CS_E_CONSTANT", column=y)
n = len(yv)
res = bf.anova_bf(yv, codes, nlev, list(factor_cols), r=r, which=which)
models = res["models"]
best = res["best"]
labels = res["labels"]
full = models[-1]
# %% Assumptions (cells = factor combinations)
cell = df[factor_cols].astype(str).agg(" · ".join, axis=1).to_numpy()
cells = sorted(set(cell))
means = {c: yv[cell == c].mean() for c in cells}
resid = yv - np.array([means[c] for c in cell])
assumptions = []
if 3 <= n <= 5000:
sw = stats.shapiro(resid)
status = "warn" if sw.pvalue < 0.05 and n < 50 else "info" if sw.pvalue < 0.05 else "pass"
detail = f"Shapiro–Wilk on residuals from the cell means: W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}."
else:
status, detail = "info", "Too few (or too many) rows for Shapiro–Wilk on the residuals."
assumptions.append({"key": "normality", "label": "Normal residuals", "status": status, "detail": detail})
dev = [np.abs(yv[cell == c] - np.median(yv[cell == c])) for c in cells]
k = len(cells)
if n > k and k > 1:
grand = np.concatenate(dev).mean()
ssb = sum(len(d) * (d.mean() - grand) ** 2 for d in dev)
ssw = sum(((d - d.mean()) ** 2).sum() for d in dev)
f_bf = (ssb / (k - 1)) / (ssw / (n - k)) if ssw > 0 else float("inf")
p_bf = float(stats.f.sf(f_bf, k - 1, n - k))
assumptions.append({"key": "equal_variance", "label": "Equal variances", "status": "warn" if p_bf < 0.05 else "pass",
"detail": f"Brown–Forsythe across {k} cells: F = {f_bf:.2f}, {cs.fmt_p(p_bf)}.", "statistic": float(f_bf), "p": p_bf})
assumptions.append({"key": "independence", "label": "Independent observations", "status": "info",
"detail": "Between-subjects factors only: each row a separate subject."})
# %% Result
label = bf.evidence_label(best["bf"])
summary = (
f"The best-supported model is {best['model']}: BF = {cs.fmt_num(best['bf'])} against the intercept-only model ({label}), "
f"posterior probability {best['posterior']:.3f} with equal prior odds over {len(models)} model(s) and the null (prior width r = {r:.3g})."
)
if len(labels) > 1:
summary += " Inclusion Bayes factors: " + "; ".join(f"{t} {cs.fmt_num(v)}" for t, v in res["inclusion"].items()) + "."
incl = res["inclusion"]
cell_rows = [{"cell": c, "n": int((cell == c).sum()), "mean": float(yv[cell == c].mean()),
"sd": float(yv[cell == c].std(ddof=1)) if (cell == c).sum() > 1 else None} for c in cells]
cs.publish({
"method": "bayes.anova",
"methodVersion": "1.0.1",
"title": "Bayesian ANOVA",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"BF = {cs.fmt_num(best['bf'])} for {best['model']} vs the intercept-only model (r = {r:.3g})",
"statistics": [
{"key": "bf_best", "label": f"BF ({best['model']} vs null)", "value": best["bf"]},
{"key": "p_best", "label": "P(best model | data)", "value": best["posterior"]},
] + [{"key": f"incl_{i}", "label": f"Inclusion BF: {t}", "value": v} for i, (t, v) in enumerate(incl.items())],
"tables": [
{"key": "models", "title": "Models (against the intercept-only model)",
"columns": [{"key": "model", "label": "Model", "type": "string"}, {"key": "bf", "label": "BF", "type": "number"},
{"key": "log_bf", "label": "log BF", "type": "number"}, {"key": "posterior", "label": "P(model | data)", "type": "number"},
{"key": "error", "label": "Error %", "type": "number"}],
"rows": [{"model": "Intercept only", "bf": 1.0, "log_bf": 0.0, "posterior": res["null_posterior"], "error": 0.0}]
+ [{"model": m["model"], "bf": m["bf"], "log_bf": m["log_bf"], "posterior": m["posterior"], "error": 100 * m["error"]} for m in models]},
{"key": "inclusion", "title": "Inclusion Bayes factors",
"columns": [{"key": "term", "label": "Term", "type": "string"}, {"key": "bf", "label": "BF (inclusion)", "type": "number"}],
"rows": [{"term": t, "bf": v} for t, v in incl.items()]},
{"key": "cells", "title": "Cell means",
"columns": [{"key": "cell", "label": " · ".join(factor_cols), "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}],
"rows": cell_rows},
],
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [
f"Each term has its own g ~ inverse-gamma(½, r²/2), r = {r:.3g}; effects use orthonormal (Helmert) contrasts; flat intercept, Jeffreys prior on σ².",
"Inclusion Bayes factors compare all models with a term against all models without it (equal prior model probabilities, null included).",
"Bayes factors are relative evidence, not p-values; they are not entered in the multiple-testing ledger.",
],
"values": {
"bf_best": best["bf"], "best_model": best["model"], "p_best": best["posterior"], "bf_full": full["bf"],
"bf_incl_1": incl[labels[0]], "bf_incl_2": incl[labels[1]] if len(labels) > 1 else None,
"bf_incl_interaction": incl[labels[2]] if len(labels) > 2 else None, "p_null": res["null_posterior"],
"n": n, "k_models": len(models), "r": r, "error_pct": 100 * max(m["error"] for m in models),
},
"charts": [cs.chart("models", "bf-models", "Bayes factors of the models",
{"model": cs.col("model", [m["model"] for m in models]), "bf": cs.col("BF", [m["bf"] for m in models]),
"posterior": cs.col("posterior", [m["posterior"] for m in models])})],
})
The exact script CodeSplash ran for example “Guide one way” · R version 4.5.1 (2025-06-13)
# Bayesian ANOVA (model comparison)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.anova 1.0.1 · spec 8b6feb244a98ff37
# Dataset: a_hetero3 (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_bayes_anova, cs_bayes_prior_scale, cs_bayes_evidence_label (twins of codesplash.stats.bayes)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/a_hetero3.parquet", col_select = c("value", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("A", "B", "C")) # stored level order
df <- df[stats::complete.cases(df[c("value", "group")]), , 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("value", "group")) # infinite values stop the run (registry/errors.yaml)
# %% Models
y <- "value"
factor_cols <- c("group")
r <- cs_bayes_prior_scale("anova", "medium", 0.5)
which <- "withmain"
codes <- list()
nlev <- integer(0)
for (f in factor_cols) {
if (nlevels(df[[f]]) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = f, min = 2, k = nlevels(df[[f]]))
codes[[length(codes) + 1]] <- as.integer(df[[f]]) - 1L
nlev <- c(nlev, nlevels(df[[f]]))
}
yv <- as.numeric(df[[y]])
if (length(unique(yv)) < 2) cs_error("CS_E_CONSTANT", column = y) # no variation: every Bayes factor is 0/0
n <- length(yv)
res <- cs_bayes_anova(yv, codes, nlev, factor_cols, r = r, which = which)
models <- res$models
best <- res$best
labels <- res$labels
full <- models[[length(models)]]
# %% Assumptions (cells = factor combinations)
cell <- do.call(paste, c(lapply(factor_cols, function(f) as.character(df[[f]])), sep = " · "))
cells <- sort(unique(cell), method = "radix")
means <- vapply(cells, function(cc) mean(yv[cell == cc]), numeric(1))
resid <- yv - means[match(cell, cells)]
assumptions <- list()
if (n >= 3 && n <= 5000) {
sw <- stats::shapiro.test(resid)
status <- if (sw$p.value < 0.05 && n < 50) "warn" else if (sw$p.value < 0.05) "info" else "pass"
detail <- sprintf("Shapiro–Wilk on residuals from the cell means: W = %.3f, %s.", sw$statistic, cs_fmt_p(sw$p.value))
} else {
status <- "info"
detail <- "Too few (or too many) rows for Shapiro–Wilk on the residuals."
}
assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Normal residuals", status = status, detail = detail)
dev <- lapply(cells, function(cc) abs(yv[cell == cc] - stats::median(yv[cell == cc])))
k <- length(cells)
if (n > k && k > 1) {
grand <- mean(unlist(dev))
ssb <- sum(vapply(dev, function(d) length(d) * (mean(d) - grand)^2, numeric(1)))
ssw <- sum(vapply(dev, function(d) sum((d - mean(d))^2), numeric(1)))
f_bf <- if (ssw > 0) (ssb / (k - 1)) / (ssw / (n - k)) else Inf
p_bf <- stats::pf(f_bf, k - 1, n - k, lower.tail = FALSE)
assumptions[[length(assumptions) + 1]] <- list(key = "equal_variance", label = "Equal variances", status = if (p_bf < 0.05) "warn" else "pass",
detail = sprintf("Brown–Forsythe across %d cells: F = %.2f, %s.", k, f_bf, cs_fmt_p(p_bf)), statistic = f_bf, p = p_bf)
}
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent observations", status = "info",
detail = "Between-subjects factors only: each row a separate subject.")
# %% Result
label <- cs_bayes_evidence_label(best$bf)
summary <- sprintf(
"The best-supported model is %s: BF = %s against the intercept-only model (%s), posterior probability %.3f with equal prior odds over %d model(s) and the null (prior width r = %s).",
best$model, cs_fmt_num(best$bf), label, best$posterior, length(models), format(signif(r, 3)))
incl <- res$inclusion
if (length(labels) > 1) {
summary <- paste0(summary, " Inclusion Bayes factors: ",
paste(vapply(names(incl), function(t) sprintf("%s %s", t, cs_fmt_num(incl[[t]])), character(1)), collapse = "; "), ".")
}
cell_rows <- lapply(cells, function(cc) {
v <- yv[cell == cc]
list(cell = cc, n = length(v), mean = mean(v), sd = if (length(v) > 1) stats::sd(v) else NULL)
})
stat_rows <- c(
list(list(key = "bf_best", label = sprintf("BF (%s vs null)", best$model), value = best$bf),
list(key = "p_best", label = "P(best model | data)", value = best$posterior)),
lapply(seq_along(incl), function(i) list(key = sprintf("incl_%d", i - 1L), label = sprintf("Inclusion BF: %s", names(incl)[i]), value = incl[[i]]))
)
cs_publish(list(
method = "bayes.anova",
methodVersion = "1.0.1",
title = "Bayesian ANOVA",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("BF = %s for %s vs the intercept-only model (r = %s)", cs_fmt_num(best$bf), best$model, format(signif(r, 3))),
statistics = stat_rows,
tables = list(
list(key = "models", title = "Models (against the intercept-only model)",
columns = list(list(key = "model", label = "Model", type = "string"), list(key = "bf", label = "BF", type = "number"),
list(key = "log_bf", label = "log BF", type = "number"), list(key = "posterior", label = "P(model | data)", type = "number"),
list(key = "error", label = "Error %", type = "number")),
rows = c(list(list(model = "Intercept only", bf = 1, log_bf = 0, posterior = res$null_posterior, error = 0)),
lapply(models, function(m) list(model = m$model, bf = m$bf, log_bf = m$log_bf, posterior = m$posterior, error = 100 * m$error)))),
list(key = "inclusion", title = "Inclusion Bayes factors",
columns = list(list(key = "term", label = "Term", type = "string"), list(key = "bf", label = "BF (inclusion)", type = "number")),
rows = lapply(names(incl), function(t) list(term = t, bf = incl[[t]]))),
list(key = "cells", title = "Cell means",
columns = list(list(key = "cell", label = paste(factor_cols, collapse = " · "), type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number")),
rows = cell_rows)
),
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(
sprintf("Each term has its own g ~ inverse-gamma(½, r²/2), r = %s; effects use orthonormal (Helmert) contrasts; flat intercept, Jeffreys prior on σ².", format(signif(r, 3))),
"Inclusion Bayes factors compare all models with a term against all models without it (equal prior model probabilities, null included).",
"Bayes factors are relative evidence, not p-values; they are not entered in the multiple-testing ledger."
),
values = list(
bf_best = best$bf, best_model = best$model, p_best = best$posterior, bf_full = full$bf,
bf_incl_1 = incl[[labels[1]]], bf_incl_2 = if (length(labels) > 1) incl[[labels[2]]] else NULL,
bf_incl_interaction = if (length(labels) > 2) incl[[labels[3]]] else NULL, p_null = res$null_posterior,
n = n, k_models = length(models), r = r, error_pct = 100 * max(vapply(models, function(m) m$error, numeric(1)))
),
charts = list(cs_chart("models", "bf-models", "Bayes factors of the models",
list(model = cs_col("model", vapply(models, function(m) m$model, character(1))),
bf = cs_col("BF", vapply(models, function(m) m$bf, numeric(1))),
posterior = cs_col("posterior", vapply(models, function(m) m$posterior, numeric(1))))))
))
Sources
- Rouder, J. N., Morey, R. D., Speckman, P. L., & Province, J. M. (2012). Default Bayes factors for ANOVA designs. Journal of Mathematical Psychology, 56, 356–374.
- Liang, F., Paulo, R., Molina, G., Clyde, M. A., & Berger, J. O. (2008). Mixtures of g priors for Bayesian variable selection. JASA, 103, 410–423.
- van den Bergh, D., et al. (2020). A tutorial on conducting and interpreting a Bayesian ANOVA in JASP. L'Année psychologique, 120, 73–96.
From the CodeSplash method registry · bayes.anova v1.0.1.