Skip to content

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.

Advanced ~11 min10 steps

What runs in CodeSplash

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

Read first

01

A table of counts, two hypotheses

Read

H0H_0 says the row and column variables are independent. H1H_1 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.

02

How were the counts collected?

Predict

Predict 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?

Row totals fixedTotal fixedNothing fixed
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.

03

Same table, different plans

In the app
Bayesian contingency tableRecorded · Python and R agreeRecorded 2026-11-17 · 14 values compared
R

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

Bayes factor across prior concentrationsWould a wider or narrower prior change the conclusion?
View data
BF₁₀prior concentration a
0.20260.1000
0.21620.1155
0.22440.1334
0.22290.1540
0.20450.1778
0.15660.2054
0.05710.2371
0.13830.2738
0.52950.3162
1.3990.3652
3.9850.4217
36.4670.4870
11.0290.5623
6.4230.6494
5.2130.7499
4.7290.8660
4.5141
4.4251.155
4.3991.334
4.4051.540
4.4241.778
4.4422.054
4.4502.371
4.4432.738
4.4153.162
4.3623.652
4.2854.217
4.1814.870
4.0545.623
3.9046.494
3.7367.499
3.5558.660
3.36410

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 \ outcomeyesnoTotal
A181230
B92130

Bayes factor by sampling plan

Sampling planBF₁₀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
))
Python

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 \ outcomeyesnoTotal
A181230
B92130

Bayes factor by sampling plan

Sampling planBF₁₀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 aa = 1:

PlanBF10\text{BF}_{10}
Row totals fixed4.51
Column totals fixed4.56
Total fixed6.66
Nothing fixed8.75
Both margins fixed2.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.

04

Both margins fixed

Read

Both 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 aa = 2.5, the same counts give BF10\text{BF}_{10} = 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.

05

The prior concentration

Predict

Predict first

The prior concentration aa is set per cell, and a=1a = 1 is uniform over cell probabilities.

As aa grows, where does H1H_1's prior shrink the cell probabilities?

Toward independenceAway from independenceIt doesn't affect them
Reveal

Toward independence, or equal cell probabilities. H1H_1 then predicts tables closer to what H0H_0 predicts, so the Bayes factor has less room to favor either. The chart Bayes factor across prior concentrations shows the change.

06

Large tables

Read

With 592 people classified on hair and eye color, the log Bayes factor is 55.8, so BF10\text{BF}_{10} 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.

07

Write the report

Reflect

You've now seen four Bayesian tests. A complete report has:

  1. The hypotheses and the prior, with its scale.
  2. The Bayes factor with its direction (BF10\text{BF}_{10} or BF01\text{BF}_{01}).
  3. An estimate, with an interval, when one exists.
  4. The robustness range.
  5. Any stopping rule.

Write one for the table above: "Assuming fixed row totals and a uniform prior, BF10\text{BF}_{10} = …". What's still missing for a reader who wants the effect's size?

08

Check your understanding

Checkpoint

Check 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

BF10\text{BF}_{10} = 4.5142 with even prior odds. What is P(H1∣data)P(H_1 \mid \text{data})? Give two decimals.

Show the answer

Answer: 0.818648937382978

4.5142/5.5142≈0.824.5142 / 5.5142 \approx 0.82.

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.

09

Do it in CodeSplash

In the app

Choose Rows and Columns, with Counts (optional) if your data are already tallied. Then choose How the counts were collected.

Python
# 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
R
# install.packages("BayesFactor")
library(BayesFactor)
tab <- as.table(HairEyeColor[, , "Female"] + HairEyeColor[, , "Male"])
contingencyTableBF(tab, sampleType = "jointMulti")
10

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 aa shrinks H1H_1 toward independence.
  • Report the prior, the Bayes factor, the range and a look at which cells matter.

Concepts in this lesson