Skip to content

BCompare groups · Guide test 314

Bayesian contingency table tests

Compare independence and association models with Bayes factors appropriate to the sampling plan and priors.

Runs in CodeSplashPython (calls R) example not runR example validated Corrected in edition 2

Do it in CodeSplash

In the app, set it up in Analyze with this method:

In Bayesian contingency table (Gunel–Dickey Bayes factor), choose How the counts were collected = Row totals fixed.

Do it in CodeSplash Run this test on your own data, in Python or R.

Bench

Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.

Bench · Bayesian contingency-table test

120
0.30

0 = rows and columns independent.

0.050

Your data

Edit the counts
LowMidHighTotal
Row A
23E = 18.1
17E = 19.1
22E = 24.8
62
Row B
12E = 16.9
20E = 17.9
26E = 23.2
58
Total353748120

E is the count expected if rows and columns were unrelated.

If H₀ were true

χ² = 3.90
  1. The reference: how χ² varies across samples when H₀ is true.
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .142).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The evidence

extremevery strongstrongmoderateanecdotalanecdotalmoderatestrongvery strongextreme1/1001/301/101/3131030100← evidence for H₀evidence for H₁ →

BF₁₀ = 0.51: anecdotal evidence for H₀ (prior: Dirichlet(1, …, 1) for each row (row totals fixed)). Unlike p, the Bayes factor can favor H₀, and it moves with the prior's width.

The formula

BF10=∏iB(yi⋅+a)/B(a1)B(y⋅⋅+ξ)/B(ξ),ξj=aI−(I−1)\mathrm{BF}_{10}=\frac{\prod_i B(\mathbf y_{i\cdot}+a)/B(a\mathbf 1)}{B(\mathbf y_{\cdot\cdot}+\xi)/B(\xi)},\qquad \xi_j=aI-(I-1)

With your numbers

χ2=3.90, ν=2 ⇒ log⁡BF10=(−0.66), BF10=0.51\chi^2 = 3.90,\ \nu = 2\ \Rightarrow\ \log\mathrm{BF}_{10} = (-0.66),\ \mathrm{BF}_{10} = 0.51
B(⋅)B(\cdot)
the multivariate beta function
aa
Dirichlet prior concentration (1 = uniform) for each row's proportions

The verdict

χ²(2) = 3.90, p = .142, BF₁₀ = 0.51

p > α = .050: compatible with H₀

Effect size: Bayes factor (H₁ over H₀) BF₁₀ = 0.515

The Bayes factor depends on the sampling plan (rows fixed here); choose the plan that matches how the data were collected, not the one that gives the biggest number.

Statistic
3.905
p-value
0.1419
Bayesian contingency-table test on a 2 × 3 table of 120 counts: χ²(2) = 3.90, p = .142, BF10 = 0.51. The p-value is above α = .050, so the data are compatible with H0.

Bayesian contingency-table test on a 2 × 3 table of 120 counts: χ²(2) = 3.90, p = .142, BF₁₀ = 0.51. The p-value is above α = .050, so the data are compatible with H₀.

Question and hypotheses

H0: row and column categories are independent; H1: association under a specified prior and sampling plan.

Assumptions

A specified likelihood and prior under each hypothesis; observations satisfy the chosen sampling model. Bayes factors measure relative predictive evidence and are not p values. Independent categorical observations; fixed margins/total or Poisson sampling must match the design.

Formula

m1∝B(α+n)B(α)m0∝B(a+nrow)B(a)B(b+ncol)B(b)BF10=m1/m0\begin{gathered}m_1\propto\frac{B(\alpha+n)}{B(\alpha)}\\[5pt] m_0\propto\frac{B(a+n_{row})}{B(a)}\frac{B(b+n_{col})}{B(b)}\\[5pt] BF_{10}=m_1/m_0\end{gathered}

Parameters and notation

Displayed joint-multinomial Dirichlet construction: α cell prior vector; a,b row/column prior vectors; B(v)=∏Γ(vj)/Γ(Σvj). Common multinomial count factors cancel. Günel–Dickey specifies linked prior choices and distinct Poisson, joint/independent multinomial and fixed-both-margins models.

Structure of the method

Compute marginal likelihoods for categorical independence and association under the sampling plan, using compatible Dirichlet-type priors or the appropriate conditional construction. Fixed total, fixed row totals, fixed both margins and Poisson sampling lead to different evidence calculations; one joint-multinomial beta-function identity cannot replace them all.

Estimated and nuisance parameters

Cell, row and column probabilities or rates are model parameters integrated out. Prior concentration and prior model odds are externally specified hyperparameters. Observed margins may be fixed by design or random outcomes; that distinction is not inferred by choosing whichever formula yields stronger evidence.

Settings and design choices

Prespecify sampleType, fixedMargin where relevant, concentration and category structure. The baseline code uses independent multinomials with fixed row totals, whereas the displayed beta-function illustration is joint multinomial. State that distinction so users do not implement the schematic equation and expect identical output.

Fitting and adaptation

Fit the correct sampling-plan model and conduct a planned prior-concentration sensitivity analysis. If structural zeros or dependent observations occur, specify a compatible extended model rather than treating them as ordinary sampling zeros. This is Bayesian evidence computation, not fine-tuning a classifier or optimizing concentration for significance.

Sensitivity and robustness

Sparse tables can be highly prior-sensitive; large tables require careful interpretation of what association model is being compared. Changing category aggregation or which margins are fixed changes the question. Report the table, sampling design, prior and BF orientation; posterior independence probability additionally requires model odds, and evidence is not an effect-size estimate.

How to use and calibrate

Use the chosen sampling-plan formula and prior concentration; report BF orientation and sensitivity to prior concentration.

Example application

Quantify evidence for categorical independence rather than merely failing to reject it.

Interpretation and pitfalls

Watch out

Changing which margins are fixed changes the Bayes factor. A single Dirichlet formula is not valid for every sampling plan.

What changed in edition 2

  • New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.
  • Rewritten in the review: example application.
  • Example applicationsearch.r-project.org

    Identify the different sampling plans in the formula and code so readers do not expect identical marginal likelihoods.

    Corrected text

    Quantify evidence for categorical independence under the sampling design. The supplied code uses independent multinomial sampling with fixed row totals; the displayed beta-function equation is a joint-multinomial illustration and is not its direct implementation.

Python and R

Independent multinomial sampling with row totals fixed and prior concentration one; the Bayes factor changes with the sampling model and prior. Select poisson/jointMulti only when that matches the design.

Python · invokes R

Not run — Executed end to end through Rscript · needs Python standard library + Rscript; R packages: BayesFactor

# Python launcher for the complete R implementation below.
# Requires Rscript on PATH and the listed R packages.
import shutil
import subprocess
rscript = shutil.which("Rscript")
if rscript is None:
    raise RuntimeError("Install R and make Rscript available on PATH.")
r_code = r"""
tab <- matrix(c(18,12,9,21),nrow=2,byrow=TRUE)
print(BayesFactor::contingencyTableBF(tab,sampleType="indepMulti",fixedMargin="rows",priorConcentration=1))
"""
# No shell interpolation. A failed R execution raises an error in Python.
result = subprocess.run([rscript, "--vanilla", "-"], input=r_code,
                        text=True, capture_output=True)
print(result.stdout)
if result.stderr:
    print(result.stderr)
result.check_returncode()
R

Validated — Executed successfully in the validation environment · needs BayesFactor

tab <- matrix(c(18,12,9,21),nrow=2,byrow=TRUE)
print(BayesFactor::contingencyTableBF(tab,sampleType="indepMulti",fixedMargin="rows",priorConcentration=1))
Output
Bayes factor analysis
--------------
[1] Non-indep. (a=1) : 4.514167 ±0%

Against denominator:
  Null, independence, a = 1 
---
Bayes factor type: BFcontingencyTable, independent multinomial

Sources

Statistics guide v4 (historical):
Python: Executed end to end through Rscript · R: Executed successfully in the validation environment
Reference's record:
Edition 2 review: Python: skip · R: not executed (Rscript unavailable); why not run: Python: Python-to-R bridge; Rscript is unavailable. R code was not executed. Python: Not run in the reference's review: Python-to-R bridge; Rscript is unavailable. R code was not executed. R: Reviewed but not run: R wasn't available to the reference's authors.

From the CodeSplash statistics guide (v4), entry 314, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT314.