Skip to content

EProportions & counts · contingency.exact

Exact test of independence for R × C tables (Fisher–Freeman–Halton)

Are two categorical variables associated when the table is too sparse for the χ² approximation?

Fisher's exact test generalized to any R × C table (Freeman–Halton): the probability of tables with the observed margins that are no more likely than the observed one. Small tables are enumerated exactly; larger ones use a Monte Carlo p-value conditional on both margins with a seeded, engine-independent random stream. Reports the χ² and G tests, Cramér's V, expected counts and adjusted residuals alongside.

Verified in Python and R Python and R agree to 10 decimals Seeded

A real result

Example “Sparse exact”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Fisher–Freeman–Halton exact testRecorded · Python and R agreeRecorded 2026-11-17 · 27 values compared
R

Fisher–Freeman–Halton p = .653, Cramér's V = 0.27

p (exact)
.653
Pearson χ² (6 df)
4.370
p (χ², asymptotic)
.627
G² (likelihood ratio)
4.922
p (G², asymptotic)
.554

Effect size

  • Cramér's V 0.2745

Plots

Adjusted residuals (cell text: counts)What do the values of a square or rectangular result matrix look like at a glance?
View data
outcomecountblood groupadjusted residual
none7A1.294
mild2A−0.8225
moderate4A−0.6470
severe1A0.0506
none1B−1.480
mild2B0.5910
moderate4B1.448
severe0B−0.8267
none3O−0.0295
mild2O0.3537
moderate2O−0.6631
severe1O0.7350

Assumptions

  • Fixed margins — The test conditions on the row and column totals.
  • Independent observations — Each row of the data is one subject.

blood group × outcome

blood groupnonemildmoderatesevere
A7241
B1240
O3221

Expected counts under independence

blood groupnonemildmoderatesevere
A5.3102.8974.8280.9655
B2.6551.4482.4140.4828
O3.0341.6552.7590.5517
  • 1 of 30 rows were left out because a value was missing.
  • Expected counts below 5 in 92% of cells (smallest 0.48); the exact test does not rely on them.
Python

Fisher–Freeman–Halton p = .653, Cramér's V = 0.27

p (exact)
.653
Pearson χ² (6 df)
4.370
p (χ², asymptotic)
.627
G² (likelihood ratio)
4.922
p (G², asymptotic)
.554

Effect size

  • Cramér's V 0.2745

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Fixed margins — The test conditions on the row and column totals.
  • Independent observations — Each row of the data is one subject.

blood group × outcome

blood groupnonemildmoderatesevere
A7241
B1240
O3221

Expected counts under independence

blood groupnonemildmoderatesevere
A5.3102.8974.8280.9655
B2.6551.4482.4140.4828
O3.0341.6552.7590.5517
  • 1 of 30 rows were left out because a value was missing.
  • Expected counts below 5 in 92% of cells (smallest 0.48); the exact test does not rely on them.

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

  • Sparse exacts4_sparse · cols: outcome · rows: blood group
  • Job monte carlos4_job · cols: satisfaction · rows: income
  • Two by two exactsmall_trial · cols: response · rows: arm
  • Hair eye mchair_eye · cols: eye · rows: hair
  • Degenerate single levels4_sparse · cols: outcome · rows: blood group

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
  • Expected counts ≥ 5? otherwise exact tests · Statistics Guide · E — Compare proportions / frequencies

What you need

Row variablecategorical / boolean · 1 column · 2–30 levels
The variable whose levels form the table's rows.
Column variablecategorical / boolean · 1 column · 2–30 levels
The variable whose levels form the table's columns.

Choices you make

hypothesis

p-valuedefault auto

How the p-value is found: enumerate every table (exact, small tables) or simulate tables with the same margins.

  • Automatic: exact for small tables, else Monte Carlo(default) — Uses exact enumeration for small tables and Monte Carlo otherwise; the usual choice.
  • Exact (enumerate every table; small tables only) — Enumerates every table with the same margins; for small tables only.
  • Monte Carlo conditional on the margins — Samples tables with the same margins; pick it for large tables, and the seed fixes the result.
Monte Carlo tablesdefault 10000

Number of simulated tables behind the Monte Carlo p-value. More is more precise but slower.

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.

  • Fixed margins

    The exact test conditions on both margins (row and column totals).

  • Independent observations

    Each subject contributes one row.

What it reports

  • Tests: Independence of the two variables
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.
method_used
How the p-value was found: exact (every table enumerated) or monte-carlo (random tables simulated).
p
How surprising your data would be if the null hypothesis were true, as a probability.
simulations
A p-value estimated from simulated or resampled statistics, with its own small sampling error.
table_bound
Upper bound on how many tables share the observed margins. Above a fixed limit, Automatic uses Monte Carlo instead.
chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
chi2_df
How much independent information is left to estimate variability after fitting the model.
chi2_p
How surprising your data would be if the null hypothesis were true, as a probability.
g2
A sum of squared, scaled differences between observed and expected counts or estimates.
g2_p
How surprising your data would be if the null hypothesis were true, as a probability.
cramers_v
Association strength in a contingency table, from 0 (none) to 1 (perfect).
min_expected
The counts a contingency table would have if the variables were independent; χ² needs them not too small.
share_expected_lt5
The counts a contingency table would have if the variables were independent; χ² needs them not too small.

Per group, level or term: adj_resid[<row> | <col>]

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

  • Exact p: R calls fisher.test (network algorithm); Python enumerates every table with the observed margins (used only when an upper bound on their number is ≤ 200,000 — both engines apply the same rule). Both count tables no more probable than the observed one with relative tolerance 1 + 1e-7.
  • Monte Carlo p: both engines permute the column codes against the row codes with the shared Wichmann–Hill stream (identical tables), p = (1 + #{P* ≤ P_obs}) / (B + 1); fisher.test(simulate.p.value = TRUE) is the classic equivalent with R's own random numbers.
Python

The exact script CodeSplash ran for example “Sparse exact” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Exact test of independence for R × C tables (Fisher–Freeman–Halton)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.exact 1.0.1 · spec 0b0122ad4abbc159
# Dataset: s4_sparse (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
from scipy import stats

import codesplash as cs
from codesplash.stats import categorical_adv as cat  # exact / Monte Carlo Fisher–Freeman–Halton (twins of codesplashr)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s4_sparse.parquet", columns=["blood group", "outcome"])
n_input = len(df)
df["blood group"] = pd.Categorical(df["blood group"], categories=["A", "B", "O"])  # stored level order
df["outcome"] = pd.Categorical(df["outcome"], categories=["none", "mild", "moderate", "severe"])  # stored level order
df = df.dropna(subset=["blood group", "outcome"])  # listwise deletion over the analysis columns
df["blood group"] = df["blood 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, ["blood group", "outcome"])  # infinite values stop the run (registry/errors.yaml)

# %% Table
rv, cv = "blood group", "outcome"
rlev = [str(v) for v in df[rv].cat.categories]
clev = [str(v) for v in df[cv].cat.categories]
rows = df[rv].cat.codes.to_numpy(dtype=np.int64)  # 0-based codes in stored level order
cols = df[cv].cat.codes.to_numpy(dtype=np.int64)
nr, nc = len(rlev), len(clev)
if nr < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=rv, min=2, k=nr)
if nc < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=cv, min=2, k=nc)
tab = np.bincount(rows * nc + cols, minlength=nr * nc).reshape(nr, nc)
n = int(tab.sum())
expected = np.outer(tab.sum(axis=1), tab.sum(axis=0)) / n

# %% Fisher–Freeman–Halton test
method = "auto"
b = int(10000)
seed = 42  # shared Wichmann–Hill stream: the same Monte Carlo tables in Python and R
bound = cat.table_bound(tab)  # upper bound on the number of tables with these margins
exact = method == "exact" or (method == "auto" and bound <= cat.EXACT_LIMIT)
if exact and bound > cat.EXACT_LIMIT:
    raise ValueError(f"Too many tables to enumerate (more than {cat.EXACT_LIMIT:,}); use the Monte Carlo p-value")
if exact:
    p = cat.fisher_exact_rxc(tab)
    method_used = "exact"
else:
    p = cat.fisher_mc(rows, cols, nr, nc, b, seed)
    method_used = "monte-carlo"

# %% Companion statistics
chi2 = float(np.sum((tab - expected) ** 2 / expected))
dfree = (nr - 1) * (nc - 1)
with np.errstate(divide="ignore", invalid="ignore"):
    g2 = float(2 * np.sum(np.where(tab > 0, tab * np.log(tab / expected), 0.0)))
v = math.sqrt(chi2 / (n * (min(nr, nc) - 1)))
pr, pc = tab.sum(axis=1) / n, tab.sum(axis=0) / n
adj = (tab - expected) / np.sqrt(expected * np.outer(1 - pr, 1 - pc))
low_share = float(np.mean(expected < 5))

# %% Assumptions
assumptions = [
    {"key": "margins", "label": "Fixed margins", "status": "info", "detail": "The test conditions on the row and column totals."},
    {"key": "independence", "label": "Independent observations", "status": "info", "detail": "Each row of the data is one subject."},
]
if not exact:
    warnings.append(f"Monte Carlo p-value from {b:,} random tables with the observed margins (seed {seed}); its standard error is about {math.sqrt(max(p * (1 - p), 1e-12) / b):.4f}.")

# %% Result
values = {
    "n": n, "n_rows": nr, "n_cols": nc, "method_used": method_used, "p": p, "simulations": b if not exact else 0,
    "table_bound": int(bound), "chi2": chi2, "chi2_df": dfree, "chi2_p": float(stats.chi2.sf(chi2, dfree)),
    "g2": g2, "g2_p": float(stats.chi2.sf(g2, dfree)), "cramers_v": v, "min_expected": float(expected.min()), "share_expected_lt5": low_share,
}
cells = []
for i in range(nr):
    for j in range(nc):
        values[f"adj_resid[{rlev[i]} | {clev[j]}]"] = float(adj[i, j])
        cells.append((rlev[i], clev[j], float(adj[i, j]), f"{int(tab[i, j])}"))
cs.publish({
    "method": "contingency.exact",
    "methodVersion": "1.0.1",
    "title": "Fisher–Freeman–Halton exact test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": f"{nr} × {nc} table of {n} observations: {'exact' if exact else 'Monte Carlo'} Fisher–Freeman–Halton test {cs.fmt_p(p)}, Cramér's V = {v:.2f}.",
    "apa": f"Fisher–Freeman–Halton {cs.fmt_p(p)}, Cramér's V = {cs.fmt_num(v)}",
    "statistics": [
        {"key": "p", "label": f"p ({'exact' if exact else 'Monte Carlo'})", "value": p, "format": "p"},
        {"key": "chi2", "label": f"Pearson χ² ({dfree} df)", "value": chi2},
        {"key": "chi2_p", "label": "p (χ², asymptotic)", "value": values["chi2_p"], "format": "p"},
        {"key": "g2", "label": "G² (likelihood ratio)", "value": g2},
        {"key": "g2_p", "label": "p (G², asymptotic)", "value": values["g2_p"], "format": "p"},
    ],
    "tables": [
        {"key": "counts", "title": f"{rv} × {cv}",
         "columns": [{"key": "row", "label": rv, "type": "string"}] + [{"key": f"c{j}", "label": lv, "type": "integer"} for j, lv in enumerate(clev)],
         "rows": [{"row": rl, **{f"c{j}": int(tab[i, j]) for j in range(nc)}} for i, rl in enumerate(rlev)]},
        {"key": "expected", "title": "Expected counts under independence",
         "columns": [{"key": "row", "label": rv, "type": "string"}] + [{"key": f"c{j}", "label": lv, "type": "number"} for j, lv in enumerate(clev)],
         "rows": [{"row": rl, **{f"c{j}": float(expected[i, j]) for j in range(nc)}} for i, rl in enumerate(rlev)]},
    ],
    "effectSizes": [{"key": "cramers_v", "label": "Cramér's V", "value": v, "method": "√(χ² / (n (min(R, C) − 1)))"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Expected counts below 5 in {low_share:.0%} of cells (smallest {expected.min():.2f}); the exact test does not rely on them."],
    "charts": [cs.chart("residuals", "matrix-heatmap", "Adjusted residuals (cell text: counts)",
                        {"row": cs.col(rv, [c[0] for c in cells]), "col": cs.col(cv, [c[1] for c in cells]),
                         "value": cs.col("adjusted residual", [c[2] for c in cells]), "label": cs.col("count", [c[3] for c in cells])},
                        controls={"scale": "diverging"})],
    "values": values,
})
R

The exact script CodeSplash ran for example “Sparse exact” · R version 4.5.1 (2025-06-13)

# Exact test of independence for R × C tables (Fisher–Freeman–Halton)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.exact 1.0.1 · spec 0b0122ad4abbc159
# Dataset: s4_sparse (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_cat_table_bound, cs_cat_fisher_mc (twins of codesplash.stats.categorical_adv)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s4_sparse.parquet", col_select = c("blood group", "outcome")))
n_input <- nrow(df)
df[["blood group"]] <- factor(df[["blood group"]], levels = c("A", "B", "O"))  # stored level order
df[["outcome"]] <- factor(df[["outcome"]], levels = c("none", "mild", "moderate", "severe"))  # stored level order
df <- df[stats::complete.cases(df[c("blood group", "outcome")]), , 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("blood group", "outcome"))  # infinite values stop the run (registry/errors.yaml)

# %% Table
rv <- "blood group"
cv <- "outcome"
rlev <- levels(df[[rv]])
clev <- levels(df[[cv]])
rows <- as.integer(df[[rv]])  # 1-based codes in stored level order
cols <- as.integer(df[[cv]])
nr <- length(rlev)
nc <- length(clev)
if (nr < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = rv, min = 2, k = nr)
if (nc < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = cv, min = 2, k = nc)
tab <- table(df[[rv]], df[[cv]])
n <- sum(tab)
expected <- outer(rowSums(tab), colSums(tab)) / n

# %% Fisher–Freeman–Halton test
method <- "auto"
b <- as.integer(10000)
seed <- 42  # shared Wichmann–Hill stream: the same Monte Carlo tables in Python and R
bound <- cs_cat_table_bound(tab)  # upper bound on the number of tables with these margins
limit <- 200000
exact <- method == "exact" || (method == "auto" && bound <= limit)
if (exact && bound > limit) stop("Too many tables to enumerate (more than 200,000); use the Monte Carlo p-value")
if (exact) {
  p <- stats::fisher.test(tab, workspace = 2e8)$p.value  # network algorithm (Mehta & Patel)
  method_used <- "exact"
} else {
  # fisher.test(tab, simulate.p.value = TRUE, B = b) is the classic equivalent (R's own random numbers).
  p <- cs_cat_fisher_mc(rows, cols, nr, nc, b, seed)
  method_used <- "monte-carlo"
}

# %% Companion statistics
O <- unclass(tab) * 1
chi2 <- sum((O - expected)^2 / expected)
dfree <- (nr - 1) * (nc - 1)
g2 <- 2 * sum(ifelse(O > 0, O * log(O / expected), 0))
v <- sqrt(chi2 / (n * (min(nr, nc) - 1)))
pr <- rowSums(O) / n
pc <- colSums(O) / n
adj <- (O - expected) / sqrt(expected * outer(1 - pr, 1 - pc))
low_share <- mean(expected < 5)

# %% Assumptions
assumptions <- list(
  list(key = "margins", label = "Fixed margins", status = "info", detail = "The test conditions on the row and column totals."),
  list(key = "independence", label = "Independent observations", status = "info", detail = "Each row of the data is one subject.")
)
if (!exact) {
  warnings <- c(warnings, sprintf("Monte Carlo p-value from %s random tables with the observed margins (seed %d); its standard error is about %.4f.",
                                  format(b, big.mark = ","), seed, sqrt(max(p * (1 - p), 1e-12) / b)))
}

# %% Result
values <- list(
  n = n, n_rows = nr, n_cols = nc, method_used = method_used, p = p, simulations = if (exact) 0L else b,
  table_bound = bound, chi2 = chi2, chi2_df = dfree, chi2_p = stats::pchisq(chi2, dfree, lower.tail = FALSE),
  g2 = g2, g2_p = stats::pchisq(g2, dfree, lower.tail = FALSE), cramers_v = v, min_expected = min(expected), share_expected_lt5 = low_share
)
cell_r <- character(0); cell_c <- character(0); cell_v <- numeric(0); cell_l <- character(0)
for (i in seq_len(nr)) {
  for (j in seq_len(nc)) {
    values[[sprintf("adj_resid[%s | %s]", rlev[i], clev[j])]] <- adj[i, j]
    cell_r <- c(cell_r, rlev[i]); cell_c <- c(cell_c, clev[j]); cell_v <- c(cell_v, adj[i, j]); cell_l <- c(cell_l, as.character(O[i, j]))
  }
}
table_of <- function(m, type) lapply(seq_len(nr), function(i) {
  r <- list(row = rlev[i])
  for (j in seq_len(nc)) r[[sprintf("c%d", j - 1)]] <- if (type == "integer") as.integer(m[i, j]) else m[i, j]
  r
})
cols_of <- function(type) c(list(list(key = "row", label = rv, type = "string")),
                            lapply(seq_len(nc), function(j) list(key = sprintf("c%d", j - 1), label = clev[j], type = type)))
lab <- if (exact) "exact" else "Monte Carlo"
cs_publish(list(
  method = "contingency.exact",
  methodVersion = "1.0.1",
  title = "Fisher–Freeman–Halton exact test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = sprintf("%d × %d table of %d observations: %s Fisher–Freeman–Halton test %s, Cramér's V = %.2f.", nr, nc, as.integer(n), lab, cs_fmt_p(p), v),
  apa = sprintf("Fisher–Freeman–Halton %s, Cramér's V = %s", cs_fmt_p(p), cs_fmt_num(v)),
  statistics = list(
    list(key = "p", label = sprintf("p (%s)", lab), value = p, format = "p"),
    list(key = "chi2", label = sprintf("Pearson χ² (%d df)", as.integer(dfree)), value = chi2),
    list(key = "chi2_p", label = "p (χ², asymptotic)", value = values$chi2_p, format = "p"),
    list(key = "g2", label = "G² (likelihood ratio)", value = g2),
    list(key = "g2_p", label = "p (G², asymptotic)", value = values$g2_p, format = "p")
  ),
  tables = list(
    list(key = "counts", title = sprintf("%s × %s", rv, cv), columns = cols_of("integer"), rows = table_of(O, "integer")),
    list(key = "expected", title = "Expected counts under independence", columns = cols_of("number"), rows = table_of(expected, "number"))
  ),
  effectSizes = list(list(key = "cramers_v", label = "Cramér's V", value = v, method = "√(χ² / (n (min(R, C) − 1)))")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Expected counts below 5 in %.0f%% of cells (smallest %.2f); the exact test does not rely on them.", 100 * low_share, min(expected))),
  charts = list(cs_chart("residuals", "matrix-heatmap", "Adjusted residuals (cell text: counts)",
                         list(row = cs_col(rv, cell_r), col = cs_col(cv, cell_c), value = cs_col("adjusted residual", cell_v), label = cs_col("count", cell_l)),
                         controls = list(scale = "diverging"))),
  values = values
))

Sources

  • Freeman, G. H., & Halton, J. H. (1951). Note on an exact treatment of contingency, goodness of fit and other problems of significance. Biometrika, 38, 141–149.
  • Mehta, C. R., & Patel, N. R. (1983). A network algorithm for performing Fisher's exact test in r × c contingency tables. JASA, 78, 427–434.
  • Agresti, A. (2002). Categorical Data Analysis (2nd ed.), §3.5. Wiley.

From the CodeSplash method registry · contingency.exact v1.0.1.