BBayesian · bayes.contingency
Bayesian contingency table (Gunel–Dickey Bayes factor)
How much more likely are the counts if the two categorical variables are associated than if they are independent?
Gunel & Dickey's (1974) Bayes factors for association against independence in a two-way table, for the sampling plan that produced the counts: Poisson (nothing fixed), joint multinomial (total fixed), independent multinomials (row or column totals fixed) or hypergeometric (both margins fixed, 2 × 2). Dirichlet priors with concentration a; the table compares all plans, because the plan changes the evidence.
A real result
Example “Guide rows fixed”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
BF₁₀ = 4.51 (Gunel–Dickey, independent multinomial, a = 1), N = 60
- BF₁₀ (association vs independence)
- 4.514
- BF₀₁
- 0.2215
- P(association | data), equal prior odds
- 0.8186
Plots
View data
| BF₁₀ | prior concentration a |
|---|---|
| 0.2026 | 0.1000 |
| 0.2162 | 0.1155 |
| 0.2244 | 0.1334 |
| 0.2229 | 0.1540 |
| 0.2045 | 0.1778 |
| 0.1566 | 0.2054 |
| 0.0571 | 0.2371 |
| 0.1383 | 0.2738 |
| 0.5295 | 0.3162 |
| 1.399 | 0.3652 |
| 3.985 | 0.4217 |
| 36.467 | 0.4870 |
| 11.029 | 0.5623 |
| 6.423 | 0.6494 |
| 5.213 | 0.7499 |
| 4.729 | 0.8660 |
| 4.514 | 1 |
| 4.425 | 1.155 |
| 4.399 | 1.334 |
| 4.405 | 1.540 |
| 4.424 | 1.778 |
| 4.442 | 2.054 |
| 4.450 | 2.371 |
| 4.443 | 2.738 |
| 4.415 | 3.162 |
| 4.362 | 3.652 |
| 4.285 | 4.217 |
| 4.181 | 4.870 |
| 4.054 | 5.623 |
| 3.904 | 6.494 |
| 3.736 | 7.499 |
| 3.555 | 8.660 |
| 3.364 | 10 |
Assumptions
- Independent observations — Each count should be a separate unit.
- Sampling plan matches the design — Computed for independent multinomial (row totals fixed); the plans table shows how the evidence changes with the plan.
Counts
| group \ outcome | yes | no | Total |
|---|---|---|---|
| A | 18 | 12 | 30 |
| B | 9 | 21 | 30 |
Bayes factor by sampling plan
| Sampling plan | BF₁₀ | Chosen |
|---|---|---|
| Poisson (nothing fixed) | 8.746 | |
| Joint multinomial (total fixed) | 6.664 | |
| Independent multinomial (row totals fixed) | 4.514 | ✓ |
| Independent multinomial (column totals fixed) | 4.557 | |
| Hypergeometric (both margins fixed) | 2.540 |
- Dirichlet priors with concentration a = 1 per cell; independence uses Gunel & Dickey's linked priors on the margins.
- Evidence: moderate evidence for H₁. A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger.
- Smallest expected count under independence: 13.50 (Bayes factors need no large-sample approximation).
BF₁₀ = 4.51 (Gunel–Dickey, independent multinomial, a = 1), N = 60
- BF₁₀ (association vs independence)
- 4.514
- BF₀₁
- 0.2215
- P(association | data), equal prior odds
- 0.8186
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent observations — Each count should be a separate unit.
- Sampling plan matches the design — Computed for independent multinomial (row totals fixed); the plans table shows how the evidence changes with the plan.
Counts
| group \ outcome | yes | no | Total |
|---|---|---|---|
| A | 18 | 12 | 30 |
| B | 9 | 21 | 30 |
Bayes factor by sampling plan
| Sampling plan | BF₁₀ | Chosen |
|---|---|---|
| Poisson (nothing fixed) | 8.746 | |
| Joint multinomial (total fixed) | 6.664 | |
| Independent multinomial (row totals fixed) | 4.514 | ✓ |
| Independent multinomial (column totals fixed) | 4.557 | |
| Hypergeometric (both margins fixed) | 2.540 |
- Dirichlet priors with concentration a = 1 per cell; independence uses Gunel & Dickey's linked priors on the margins.
- Evidence: moderate evidence for H₁. A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger.
- Smallest expected count under independence: 13.50 (Bayes factors need no large-sample approximation).
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 rows fixedba_ct314 · cols: outcome · rows: group · weights: count
- Guide poissonba_ct314 · cols: outcome · rows: group · weights: count
- Guide hypergeometricba_ct314 · cols: outcome · rows: group · weights: count
- Hair eye jointhair_eye · cols: eye · rows: hair
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- More than two groups, categorical: χ² independence, Fisher's exact · Statistics Guide · B — Compare groups
- Categorical–categorical: χ², Fisher, Cramér's V · Statistics Guide · C — Test association
- More than two groups: χ² independence · Statistics Guide · E — Compare proportions / frequencies
What you need
- Rowscategorical / boolean · 1 column · 2–30 levels
- The row variable (e.g. the group whose totals were fixed by design).
- Columnscategorical / boolean · 1 column · 2–30 levels
- The column variable (e.g. the outcome).
- Counts (optional)numeric · 0–1 column
- A column of cell counts when each row is a cell of the table; without it every row counts once.
Choices you make
hypothesis
- How the counts were collecteddefault rows
The sampling plan changes the Bayes factor: choose the one that matches how the data were collected.
- Row totals fixed(default) — e.g. a set number of people per group; compares the column distribution across rows.
- Column totals fixed — e.g. a set number of cases and controls; compares the row distribution across columns.
- Total fixed — A fixed number of units, each classified on both variables.
- Nothing fixed — Counts gathered over a period; even the total is random.
- Both margins fixed — Row and column totals fixed by design (Fisher's tea-tasting); 2 × 2 only.
- Prior concentration adefault 1
Dirichlet concentration per cell (1 = uniform over the cell probabilities); larger a shrinks toward independence.
Advanced
- Robustness across prior concentrationsdefault on
Recompute the Bayes factor for a from 0.1 to 10 (chart).
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.
Independent observations
Each count is a separate unit; repeated measures on a person violate it.
Empty margins
A row or column with no counts carries no information and can make the Bayes factor unstable.
Sampling plan matches the design
The Bayes factor is valid only for the plan that generated the totals.
What it reports
- bf10
- How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
- bf01
- The same Bayes factor on other scales: BF₀₁ = 1/BF₁₀ counts evidence for H₀, and log BF₁₀ is its natural log.
- log_bf10
- The same Bayes factor on other scales: BF₀₁ = 1/BF₁₀ counts evidence for H₀, and log BF₁₀ is its natural log.
- p_h1
- How probable each model is after the data, given equal prior probabilities for the models compared.
- plan
- Sampling plan assumed for the Bayes factor: poisson, joint, rows or cols fixed, or hypergeometric (both margins fixed).
- a
- Asks whether rows within groups are closer than random sets of the same sizes; A = 1 − δ/E(δ).
- n
- How many independent units the analysis used; it sets precision and power.
- n_rows
- How many independent units the analysis used; it sets precision and power.
- n_cols
- How many independent units the analysis used; it sets precision and power.
- bf_poisson
- How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
- bf_joint
- How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
- bf_rows
- How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
- bf_cols
- How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
- bf_hypergeometric
- How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- The hypergeometric Bayes factor is an exact finite sum here; BayesFactor::contingencyTableBF agrees to its printed precision.
The exact script CodeSplash ran for example “Guide rows fixed” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bayesian contingency table (Gunel–Dickey Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.contingency 1.0.2 · spec accd77b828aaf2d4
# Dataset: ba_ct314 (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 bayes as bf # Gunel–Dickey Bayes factors (twin of R cs_bayes_contingency)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ba_ct314.parquet", columns=["group", "outcome", "count"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["A", "B"]) # stored level order
df["outcome"] = pd.Categorical(df["outcome"], categories=["yes", "no"]) # stored level order
df = df.dropna(subset=["group", "outcome", "count"]) # listwise deletion over the analysis columns
df["group"] = df["group"].cat.remove_unused_categories()
df["outcome"] = df["outcome"].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, ["group", "outcome", "count"]) # infinite values stop the run (registry/errors.yaml)
# %% Table
rv, cv = "group", "outcome"
row_levels = [str(x) for x in df[rv].cat.categories]
col_levels = [str(x) for x in df[cv].cat.categories]
w = df["count"].to_numpy(dtype=float)
if (w < 0).any():
raise ValueError("Counts must be zero or positive.")
tab = np.zeros((len(row_levels), len(col_levels)))
np.add.at(tab, (df[rv].cat.codes.to_numpy(), df[cv].cat.codes.to_numpy()), w)
plan = "rows"
a = 1
if plan == "hypergeometric":
if tab.shape != (2, 2):
raise ValueError("Both-margins-fixed Bayes factors are defined for 2 × 2 tables only.")
if not np.allclose(tab, np.round(tab)):
raise ValueError("The hypergeometric plan needs whole-number counts.")
n = float(tab.sum())
log_bf = bf.contingency_bf(tab, plan, a)
bf10 = math.exp(log_bf)
plans = dict(bf.contingency_all(tab, a))
names = {"poisson": "Poisson (nothing fixed)", "joint": "Joint multinomial (total fixed)", "rows": "Independent multinomial (row totals fixed)",
"cols": "Independent multinomial (column totals fixed)", "hypergeometric": "Hypergeometric (both margins fixed)"}
# %% Assumptions
expected = np.outer(tab.sum(1), tab.sum(0)) / n
assumptions = [
{"key": "independence", "label": "Independent observations", "status": "info", "detail": "Each count should be a separate unit."},
{"key": "plan", "label": "Sampling plan matches the design", "status": "info",
"detail": f"Computed for {names[plan].lower()}; the plans table shows how the evidence changes with the plan."},
]
if (tab.sum(1) == 0).any() or (tab.sum(0) == 0).any():
assumptions.append({"key": "empty", "label": "Empty margins", "status": "warn", "detail": "A row or column has no counts."})
# %% Result
label = bf.evidence_label(bf10)
summary = (
f"BF₁₀ = {cs.fmt_num(bf10)} for an association between {rv} and {cv} ({names[plan].lower()}, prior concentration a = {a:g}, N = {n:g}): "
f"the counts are {cs.fmt_num(bf10 if bf10 >= 1 else 1 / bf10)} times more likely under {'association' if bf10 >= 1 else 'independence'} — {label}."
)
a_grid = np.unique(np.round(np.concatenate([np.exp(np.linspace(math.log(0.1), math.log(10.0), 33)), [a]]), 12))
charts = []
if True:
charts.append(cs.chart("robustness", "bf-robustness", "Bayes factor across prior concentrations",
{"x": cs.col("prior concentration a", a_grid), "bf": cs.col("BF₁₀", [math.exp(bf.contingency_bf(tab, plan, float(x))) for x in a_grid])},
controls={"chosen": a, "logX": True}))
counts_rows = [{"row": row_levels[i], **{f"c{j}": float(tab[i, j]) for j in range(len(col_levels))}, "total": float(tab[i].sum())} for i in range(len(row_levels))]
cs.publish({
"method": "bayes.contingency",
"methodVersion": "1.0.2",
"title": "Bayesian contingency table",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(round(n)),
"summary": summary,
"apa": f"BF₁₀ = {cs.fmt_num(bf10)} (Gunel–Dickey, {names[plan].split(' (')[0].lower()}, a = {a:g}), N = {n:g}",
"statistics": [
{"key": "bf10", "label": "BF₁₀ (association vs independence)", "value": bf10},
{"key": "bf01", "label": "BF₀₁", "value": 1 / bf10},
{"key": "p_h1", "label": "P(association | data), equal prior odds", "value": bf10 / (1 + bf10)},
],
"tables": [
{"key": "counts", "title": "Counts",
"columns": [{"key": "row", "label": f"{rv} \\ {cv}", "type": "string"}]
+ [{"key": f"c{j}", "label": lv, "type": "number"} for j, lv in enumerate(col_levels)]
+ [{"key": "total", "label": "Total", "type": "number"}],
"rows": counts_rows},
{"key": "plans", "title": "Bayes factor by sampling plan",
"columns": [{"key": "plan", "label": "Sampling plan", "type": "string"}, {"key": "bf", "label": "BF₁₀", "type": "number"},
{"key": "chosen", "label": "Chosen", "type": "string"}],
"rows": [{"plan": names[p], "bf": math.exp(v), "chosen": "✓" if p == plan else ""} for p, v in plans.items()]},
],
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [
f"Dirichlet priors with concentration a = {a:g} per cell; independence uses Gunel & Dickey's linked priors on the margins.",
f"Evidence: {label}. A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger.",
f"Smallest expected count under independence: {expected.min():.2f} (Bayes factors need no large-sample approximation).",
],
"values": {
"bf10": bf10, "bf01": 1 / bf10, "log_bf10": log_bf, "p_h1": bf10 / (1 + bf10), "plan": plan, "a": a, "n": n,
"n_rows": len(row_levels), "n_cols": len(col_levels),
"bf_poisson": math.exp(plans["poisson"]), "bf_joint": math.exp(plans["joint"]), "bf_rows": math.exp(plans["rows"]),
"bf_cols": math.exp(plans["cols"]), "bf_hypergeometric": math.exp(plans["hypergeometric"]) if "hypergeometric" in plans else None,
},
"charts": charts,
})
The exact script CodeSplash ran for example “Guide rows fixed” · R version 4.5.1 (2025-06-13)
# Bayesian contingency table (Gunel–Dickey Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.contingency 1.0.2 · spec accd77b828aaf2d4
# Dataset: ba_ct314 (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_contingency, cs_bayes_contingency_all, cs_bayes_evidence_label (twins of codesplash.stats.bayes)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ba_ct314.parquet", col_select = c("group", "outcome", "count")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("A", "B")) # stored level order
df[["outcome"]] <- factor(df[["outcome"]], levels = c("yes", "no")) # stored level order
df <- df[stats::complete.cases(df[c("group", "outcome", "count")]), , 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("group", "outcome", "count")) # infinite values stop the run (registry/errors.yaml)
# %% Table
rv <- "group"
cv <- "outcome"
row_levels <- levels(df[[rv]])
col_levels <- levels(df[[cv]])
w <- as.numeric(df[["count"]])
if (any(w < 0)) stop("Counts must be zero or positive.")
tab <- matrix(0, length(row_levels), length(col_levels))
ri <- as.integer(df[[rv]])
ci <- as.integer(df[[cv]])
for (i in seq_along(w)) tab[ri[i], ci[i]] <- tab[ri[i], ci[i]] + w[i]
plan <- "rows"
a <- 1
if (plan == "hypergeometric") {
if (!all(dim(tab) == 2)) stop("Both-margins-fixed Bayes factors are defined for 2 × 2 tables only.")
if (!isTRUE(all.equal(tab, round(tab)))) stop("The hypergeometric plan needs whole-number counts.")
}
n <- sum(tab)
log_bf <- cs_bayes_contingency(tab, plan, a)
bf10 <- exp(log_bf)
plans <- cs_bayes_contingency_all(tab, a)
plan_bf <- setNames(vapply(plans, function(p) exp(p$log_bf), numeric(1)), vapply(plans, function(p) p$plan, character(1)))
names_p <- c(poisson = "Poisson (nothing fixed)", joint = "Joint multinomial (total fixed)", rows = "Independent multinomial (row totals fixed)",
cols = "Independent multinomial (column totals fixed)", hypergeometric = "Hypergeometric (both margins fixed)")
# %% Assumptions
expected <- outer(rowSums(tab), colSums(tab)) / n
assumptions <- list(
list(key = "independence", label = "Independent observations", status = "info", detail = "Each count should be a separate unit."),
list(key = "plan", label = "Sampling plan matches the design", status = "info",
detail = sprintf("Computed for %s; the plans table shows how the evidence changes with the plan.", tolower(names_p[[plan]])))
)
if (any(rowSums(tab) == 0) || any(colSums(tab) == 0)) {
assumptions[[length(assumptions) + 1]] <- list(key = "empty", label = "Empty margins", status = "warn", detail = "A row or column has no counts.")
}
# %% Result
label <- cs_bayes_evidence_label(bf10)
summary <- sprintf(
"BF₁₀ = %s for an association between %s and %s (%s, prior concentration a = %s, N = %s): the counts are %s times more likely under %s — %s.",
cs_fmt_num(bf10), rv, cv, tolower(names_p[[plan]]), format(a), format(n), cs_fmt_num(if (bf10 >= 1) bf10 else 1 / bf10),
if (bf10 >= 1) "association" else "independence", label)
a_grid <- sort(unique(round(c(exp(seq(log(0.1), log(10), length.out = 33)), a), 12)))
charts <- list()
if (TRUE) {
charts[[length(charts) + 1]] <- cs_chart("robustness", "bf-robustness", "Bayes factor across prior concentrations",
list(x = cs_col("prior concentration a", a_grid), bf = cs_col("BF₁₀", vapply(a_grid, function(x) exp(cs_bayes_contingency(tab, plan, x)), numeric(1)))),
controls = list(chosen = a, logX = TRUE))
}
counts_rows <- lapply(seq_along(row_levels), function(i) {
rw <- list(row = row_levels[i])
for (j in seq_along(col_levels)) rw[[sprintf("c%d", j - 1L)]] <- tab[i, j]
rw$total <- sum(tab[i, ])
rw
})
cs_publish(list(
method = "bayes.contingency",
methodVersion = "1.0.2",
title = "Bayesian contingency table",
engine = cs_engine_info("stats", "nanoparquet"),
n = as.integer(round(n)),
summary = summary,
apa = sprintf("BF₁₀ = %s (Gunel–Dickey, %s, a = %s), N = %s", cs_fmt_num(bf10), tolower(sub(" \\(.*$", "", names_p[[plan]])), format(a), format(n)),
statistics = list(
list(key = "bf10", label = "BF₁₀ (association vs independence)", value = bf10),
list(key = "bf01", label = "BF₀₁", value = 1 / bf10),
list(key = "p_h1", label = "P(association | data), equal prior odds", value = bf10 / (1 + bf10))
),
tables = list(
list(key = "counts", title = "Counts",
columns = c(list(list(key = "row", label = sprintf("%s \\ %s", rv, cv), type = "string")),
lapply(seq_along(col_levels), function(j) list(key = sprintf("c%d", j - 1L), label = col_levels[j], type = "number")),
list(list(key = "total", label = "Total", type = "number"))),
rows = counts_rows),
list(key = "plans", title = "Bayes factor by sampling plan",
columns = list(list(key = "plan", label = "Sampling plan", type = "string"), list(key = "bf", label = "BF₁₀", type = "number"),
list(key = "chosen", label = "Chosen", type = "string")),
rows = lapply(names(plan_bf), function(p) list(plan = names_p[[p]], bf = plan_bf[[p]], chosen = if (p == plan) "✓" else "")))
),
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(
sprintf("Dirichlet priors with concentration a = %s per cell; independence uses Gunel & Dickey's linked priors on the margins.", format(a)),
sprintf("Evidence: %s. A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger.", label),
sprintf("Smallest expected count under independence: %.2f (Bayes factors need no large-sample approximation).", min(expected))
),
values = list(
bf10 = bf10, bf01 = 1 / bf10, log_bf10 = log_bf, p_h1 = bf10 / (1 + bf10), plan = plan, a = a, n = n,
n_rows = length(row_levels), n_cols = length(col_levels),
bf_poisson = plan_bf[["poisson"]], bf_joint = plan_bf[["joint"]], bf_rows = plan_bf[["rows"]], bf_cols = plan_bf[["cols"]],
bf_hypergeometric = if ("hypergeometric" %in% names(plan_bf)) plan_bf[["hypergeometric"]] else NULL
),
charts = charts
))
Sources
- Gunel, E., & Dickey, J. (1974). Bayes factors for independence in contingency tables. Biometrika, 61, 545–557.
- Jamil, T., Ly, A., Morey, R. D., Love, J., Marsman, M., & Wagenmakers, E.-J. (2017). Default 'Gunel and Dickey' Bayes factors for contingency tables. Behavior Research Methods, 49, 638–652.
From the CodeSplash method registry · bayes.contingency v1.0.2.