Bayesian contingency tables
Test association in a table with the Gunel–Dickey Bayes factor, see why your sampling plan changes the answer, and bring the track's reporting habits together.
What runs in CodeSplash
- STAT314Bayesian contingency table tests Runs in CodeSplash
- Bayesian contingency table (Gunel–Dickey Bayes factor) Verified in Python and R
You will be able to
- Match a sampling plan to how the counts were collected
- Read a Bayes factor for independence and the effect of the prior concentration
- Write a complete report of a Bayes factor analysis
A table of counts, two hypotheses
Readsays the row and column variables are independent. allows any pattern, with a Dirichlet prior on the cell probabilities. The Gunel–DickeyGunel–Dickey Bayes factorBayes factors for association in a contingency table, one per sampling plan (Poisson, multinomial, fixed margins). Bayes factor compares how well the two predict the counts.
A chi-square test needs only the table. A Bayes factor also needs to know how the table came about, because that changes what each hypothesis predicts.
How were the counts collected?
PredictPredict first
You run a survey for two weeks and count responses by age group and preference. Neither the total nor the group sizes were set in advance.
Which sampling plan fits?
Reveal
Nothing fixed: Poisson. If you had recruited exactly 100 people per age group, the plan would be Row totals fixed. If you had recruited 200 people and then classified them, it would be Total fixed.
Same table, different plans
In the appBF₁₀ = 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).
The exact R script · R 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
))
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).
The exact Python script · Python 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,
})
Open Bayes factor by sampling plan. For the same counts, with = 1:
| Plan | |
|---|---|
| Row totals fixed | 4.51 |
| Column totals fixed | 4.56 |
| Total fixed | 6.66 |
| Nothing fixed | 8.75 |
| Both margins fixed | 2.54 |
The label on the evidence could change with the plan. Choose it from the way you collected the data, not from the table it produces.
Both margins fixed
ReadBoth margins are rarely fixed in practice. Fisher's tea-tasting is the classic case: the taster knows how many cups of each kind there are, so both totals are set.
This plan only applies to 2 × 2 tables. With a concentration = 2.5, the same counts give = 3.82.
If you're tempted to choose this plan because Fisher's exact test is familiar, check whether your margins really were fixed by design.
The prior concentration
PredictPredict first
The prior concentration is set per cell, and is uniform over cell probabilities.
As grows, where does 's prior shrink the cell probabilities?
Reveal
Toward independence, or equal cell probabilities. then predicts tables closer to what predicts, so the Bayes factor has less room to favor either. The chart Bayes factor across prior concentrations shows the change.
Large tables
ReadWith 592 people classified on hair and eye color, the log Bayes factor is 55.8, so runs to many digits.
Use the log scale for values like this. Then report something that shows the pattern, because a giant Bayes factor says "not independent" and nothing about which cells drive it. Follow up with residuals or a mosaic plot.
Write the report
ReflectYou've now seen four Bayesian tests. A complete report has:
- The hypotheses and the prior, with its scale.
- The Bayes factor with its direction ( or ).
- An estimate, with an interval, when one exists.
- The robustness range.
- Any stopping rule.
Write one for the table above: "Assuming fixed row totals and a uniform prior, = …". What's still missing for a reader who wants the effect's size?
Check your understanding
CheckpointCheck yourself
You recruit 50 patients per arm and count recoveries. Which plan fits?
Show the answer
Answer: a
The arm sizes were set by design. Total recoveries weren't, so this isn't both margins fixed.
Check yourself
= 4.5142 with even prior odds. What is ? Give two decimals.
Show the answer
Answer: 0.818648937382978
.
Check yourself
Your Bayes factor is highest under Poisson, but you fixed the row totals in advance. What do you report?
Show the answer
Answer: b
The plan is a fact about how the data were collected, not a setting to tune.
Do it in CodeSplash
In the appChoose Rows and Columns, with Counts (optional) if your data are already tallied. Then choose How the counts were collected.
# BayesFactor has no standard Python twin; this is the helper the method itself uses.
import pandas as pd
from codesplash.stats import bayes as bf
df = pd.read_csv("hair_eye.csv")
tab = pd.crosstab(df["hair"], df["eye"]).to_numpy()
print(bf.contingency_bf(tab, "joint", a=1.0)) # log BF10# install.packages("BayesFactor")
library(BayesFactor)
tab <- as.table(HairEyeColor[, , "Female"] + HairEyeColor[, , "Male"])
contingencyTableBF(tab, sampleType = "jointMulti")Recap
Recap- A Bayesian contingency test needs your sampling plan, because that changes what each hypothesis predicts.
- Choose the plan from your design. Don't choose it from the Bayes factors.
- Larger shrinks toward independence.
- Report the prior, the Bayes factor, the range and a look at which cells matter.
Concepts in this lesson