Chi-Square vs Fisher's Exact Test & Cramér's V Guide: Cochran Rules & Yates
When testing categorical tables, confusing expected counts with observed frequencies or overlooking software defaults can invalidate your findings. Here is how to navigate Pearson's chi-square, Fisher's exact test, Cramér's V, and McNemar's test across Python and R.
HumanPen Team
· 15 min read
Direct Decision Matrix: Pearson χ², Fisher's Exact, and Paired McNemar
To evaluate categorical contingency tables, use Pearson's `χ²` test when observations are independent and expected cell counts satisfy Cochran's rule (zero cells with `E_ij < 1` and at least 80% of cells with `E_ij >= 5`; for a `2 × 2` table, all 4 cells require `E_ij >= 5`). When expected frequencies violate these thresholds, apply Fisher's exact test (or the Freeman-Halton extension for `R × C` tables). If binary observations represent paired pre/post measurements or matched case-control pairs, independence is violated; analyze discordant pairs using McNemar's test.
Epidemiologists, clinical trialists, and conversion analysts routinely encounter categorical frequency tables when assessing baseline demographics, evaluating adverse clinical events, or measuring experiment conversions. However, methodological reviews frequently reveal recurring statistical pitfalls: confusing observed cell counts with theoretical expected frequencies, failing to notice automated Yates' continuity corrections that artificially suppress chi-square test statistics in software defaults, conflating conditional maximum likelihood odds ratios with unconditional sample ratios, or running independent tests on repeated paired measurements. Connecting these categorical analyses with baseline clinical characteristics tables, CONSORT clinical trial secondary workflows, and A/B testing conversion metrics requires a clear understanding of cell count rules, exact inference, and effect size calculations.
| Statistical Test | Table Dimensions & Design | Sample Size & Expected Count Rule | Primary Test Statistic | Recommended Effect Size & Software Implementation |
|---|---|---|---|---|
| Pearson Chi-Square (`χ²`) | Independent `2 × 2` or `R × C` | `N >= 40`; all `E_ij >= 5` (`2 × 2`), or Cochran rule (`R × C`) | Asymptotic `χ²` distribution (`df = (r - 1)(c - 1)`) | Cramér's `V` (`scipy.stats.contingency.association`, R `chisq.test`) |
| Yates' Corrected Chi-Square | Independent `2 × 2` tables only | `N >= 40`; all `E_ij >= 5`, discrete continuity correction | Conservative `χ²` (`df = 1`), `abs(O - E) - 0.5` | Odds Ratio or Relative Risk (`scipy.stats.chi2_contingency`, R `correct = TRUE`) |
| Fisher's Exact Test | Independent `2 × 2` tables | Small sample or sparse cells (`E_ij < 5` in any cell) | Hypergeometric probability across fixed margins | Conditional MLE Odds Ratio (`scipy.stats.fisher_exact`, R `stats::fisher.test`) |
| Freeman-Halton Exact Test | Independent `R × C` tables | Sparse cells failing Cochran rule (`> 20%` cells `E_ij < 5`) | Multi-dimensional hypergeometric probability | Bias-adjusted Cramér's `V` (R `fisher.test(simulate.p.value = TRUE)`) |
| McNemar's Test | Paired binary (`2 × 2` dependent) | Repeated measures or matched pairs on same subjects | Binomial exact (`b + c < 25`) or asymptotic `χ²` (`df = 1`) | Odds Ratio of discordant pairs (`statsmodels.stats.contingency_tables.mcnemar`, R `mcnemar.test`) |
Statistical validity rests entirely on theoretical expected counts rather than observed counts: an observed count of zero does not violate Pearson's chi-square if its expected frequency is at least 5, whereas an expected count below 5 invalidates asymptotic approximations even if observed frequencies are large.
Cochran (1954) Expected-Count Rules and Yates' Continuity Correction Defaults
The most persistent misconception in categorical data analysis is evaluating cell eligibility using observed cell frequencies `O_ij` rather than theoretical expected counts `E_ij`. Under the null hypothesis that rows and columns are independent, the expected count for row `i` and column `j` is calculated as `E_ij = (Row_i × Col_j) / N`, where `Row_i` is the row marginal total, `Col_j` is the column marginal total, and `N` is the grand sample total. In his landmark methodological paper (Biometrics, 1954), William G. Cochran established the formal criteria governing when the asymptotic chi-square approximation remains valid in contingency tables: no cell may have an expected count less than 1 (`E_ij < 1`), and at least 80% of cells must have expected counts of 5 or greater (`E_ij >= 5`). In a standard `2 × 2` table containing exactly four cells, satisfying the 80% threshold mathematically requires all 4 cells (since 3 out of 4 cells represents only 75%, which fails the 80% criterion) to maintain `E_ij >= 5`. If a `2 × 2` table has even a single cell with an expected count below 5, asymptotic Pearson chi-square inference is invalid, and researchers must transition to Fisher's exact test.
A second widespread trap lies in software defaults for `2 × 2` tables. Both Python (`scipy.stats.chi2_contingency(table, correction=True)`) and R (`stats::chisq.test(table, correct = TRUE)`) apply Yates' continuity correction by default whenever degrees of freedom equal 1. Frank Yates proposed subtracting 0.5 from the absolute difference between observed and expected counts (`|O_ij - E_ij| - 0.5`) to adjust for approximating a discrete binomial sampling distribution with a continuous chi-square curve. However, theoretical biostatistics has demonstrated that Yates' correction is overly conservative, reducing statistical power and producing a `χ²` statistic that is strictly smaller than the squared z-statistic (`z²`) derived from a standard two-proportion z-test. When sample sizes are substantial (`N > 100`) and expected frequencies are comfortably above 5, authors frequently disable the correction by setting `correction=False` in SciPy or `correct = FALSE` in R to report uncorrected Pearson chi-square statistics aligned with clinical trial proportion comparisons. Crucially, Python's `scipy.stats.contingency.association(observed, method='cramer', correction=False)` defaults to uncorrected chi-square, meaning analyst scripts that mix `chi2_contingency` with `association` without setting explicit flags will report inconsistent test statistics and effect sizes for the identical table.
R's `stats::fisher.test` implements Cochran's exact parameters inside its hybrid testing interface: `hybridPars = c(expect = 5, percent = 80, Emin = 1)`. In Python and R, always verify expected frequencies programmatically and pass explicit continuity flags rather than relying on silent library defaults.
- Compute marginal row totals, column totals, and grand total `N`, calculating theoretical expected frequencies `E_ij = (Row_i × Col_j) / N` for every cell before inspecting p-values.
- Evaluate Cochran (1954) validity criteria: confirm that zero cells have `E_ij < 1` and at least 80% of cells have `E_ij >= 5` (requiring all 4 cells to have `E_ij >= 5` in `2 × 2` tables).
- Verify experimental independence: confirm that each participant or observation belongs to one and only one cell in the contingency table, ruling out repeated measures or paired tracking.
- Specify continuity correction parameters explicitly in scripts: document whether `correction=True` or `correction=False` was used in Python, matching `correct = TRUE` or `FALSE` in R.
Fisher's Exact Test: Conditional MLE vs Sample Odds Ratios in Python and R
When sample sizes are small or expected frequencies drop below 5, Fisher's exact test calculates the exact probability of observing the contingency table under the null hypothesis of independence, conditioning on both row and column marginal totals remaining fixed. However, clinicians and data scientists who run the identical `2 × 2` dataset through Python and R are often startled to find different numbers reported for the odds ratio. In Python, `scipy.stats.fisher_exact(table)` returns the unconditional sample odds ratio as its `.statistic`, calculated directly as `(a × d) / (b × c)`. In contrast, R's `stats::fisher.test(table)$estimate` computes the conditional Maximum Likelihood Estimate (MLE) of the odds ratio, which represents the noncentrality parameter of Fisher's noncentral hypergeometric distribution whose expected value matches the observed count in cell `[0, 0]`. In finite samples, the conditional MLE diverges slightly from the sample cross-product ratio, creating confusion during multi-center trial replications.
To resolve this discrepancy and ensure complete reproducibility across statistical software, Python (`SciPy v1.18.0`, introduced in `v1.10.0`) provides `scipy.stats.contingency.odds_ratio(table, kind='conditional')`. Calling `.confidence_interval(confidence_level=0.95)` on this object reproduces the exact conditional MLE odds ratio and exact hypergeometric 95% confidence interval reported by R's `stats::fisher.test()`. Alternatively, setting `kind='sample'` returns the unconditional cross-product ratio accompanied by Woolf's asymptotic log-scale 95% confidence interval. When working with Python's econometric ecosystem, `statsmodels.stats.contingency_tables.Table2x2(table)` handles sparse cells by default using `shift_zeros=True`, which adds a 0.5 Haldane–Anscombe continuity correction across all cells if any observed frequency equals zero to prevent undefined division by zero. Specifying whether an analysis relies on conditional MLE or sample cross-products eliminates discrepancies between biostatistical analysis plans and computational outputs.
When contingency tables expand beyond `2 × 2` dimensions into `R × C` designs (such as evaluating 3 treatment dosages across 4 clinical symptom grades) and cell counts violate Cochran's conditions, researchers must transition to the Freeman-Halton extension of Fisher's exact test. Unlike asymptotic chi-square tests that rely on continuous approximations, exact tests compute the joint multinomial-hypergeometric probability across all possible table configurations preserving the observed marginal totals. In R, `stats::fisher.test(table)` evaluates `R × C` tables directly; when table dimensions or marginal counts become too large for exhaustive network enumeration, analysts set `simulate.p.value = TRUE` with `B = 2000` (or higher) to obtain an exact Monte Carlo p-value. In Python, modern SciPy (`v1.18.0`) natively supports `R × C` contingency tables inside `scipy.stats.fisher_exact`, returning the exact hypergeometric probability mass and two-sided p-value.
Odds Ratios approximate Relative Risk (RR) accurately only under the rare disease assumption when outcome incidence is below 10%. In prospective randomized trials or cohorts with common endpoints, reporting Odds Ratios can substantially exaggerate treatment effects; compute Relative Risk and risk differences alongside ORs.
Cramér's V, Standardized Residuals, and Paired Binary McNemar Tests
Statistical significance indicates only that categorical variables are unlikely to be independent; it conveys nothing about the practical strength of their association. The standard effect size metric for contingency tables is Cramér's `V`, formulated as `V = sqrt((χ² / N) / min(r - 1, c - 1))`, where `χ²` is the uncorrected Pearson chi-square statistic, `N` is total sample size, and `r` and `c` represent row and column counts. A notorious formula error in tutorial literature mistakenly divides by `(r - 1)(c - 1)` inside the denominator. Dividing by `sqrt((r - 1)(c - 1))` computes Tschuprow's `T`, an alternative metric that cannot reach 1.0 in rectangular tables where row and column counts differ, whereas Cramér's `V` correctly scales association strength between 0.0 (no association) and 1.0 (perfect association) across all rectangular dimensions. In R, `effectsize::cramers_v(table)` applies Bergsma (2013) finite-sample bias correction by default (`adjust = TRUE`), while Python's `scipy.stats.contingency.association(table, method='cramer')` calculates the unadjusted classical Cramér's `V`.
When an `R × C` contingency table produces a statistically significant chi-square statistic, the omnibus test does not reveal which specific cell combinations are responsible for the departure from independence. To locate the sources of association without inflating false positive rates through uncontrolled pairwise testing, researchers compute adjusted standardized Pearson residuals: `r_ij = (O_ij - E_ij) / sqrt(E_ij × (1 - p_i) × (1 - p_j))`, where `p_i` is the row marginal proportion and `p_j` is the column marginal proportion. Under the null hypothesis of independence, each adjusted standardized residual asymptotically follows a standard normal distribution `N(0, 1)`. Cells exhibiting residual values with an absolute magnitude exceeding 1.96 indicate statistically significant differences at the 0.05 alpha level, while values exceeding Bonferroni-adjusted thresholds (such as `|r_ij| > 2.58` or `3.0`) pinpoint the specific category interactions driving the overall clinical or behavioral association.
Both Pearson's chi-square and Fisher's exact tests strictly presuppose independent sampling units. Applying independent contingency tests to repeated binary evaluations of the same participants (such as pre-treatment versus post-treatment infection status), matched case-control studies, or head-to-head comparisons of two diagnostic classifiers evaluated on the same patient cohort severely violates the independence assumption. Matched binary structures must be evaluated using McNemar's test (`statsmodels.stats.contingency_tables.mcnemar` in Python or R's `stats::mcnemar.test`). McNemar's test disregards concordant pairs (cases where both evaluations agree, cells `a` and `d`) and evaluates symmetry solely across discordant pairs: cell `b` (positive at baseline, negative at outcome) and cell `c` (negative at baseline, positive at outcome). When discordant frequency totals are small (`b + c < 25`), asymptotic chi-square approximations deteriorate, and researchers must specify exact binomial calculations (`exact=True` in `statsmodels`, or R's `binom.test(b, b + c, p = 0.5)`).
For paired binary evaluations, concordant pairs provide zero evidence regarding marginal change; test power and effect estimates are governed entirely by discordant transitions, evaluated using exact binomial tests when discordant totals drop below 25.
Generating Verified Contingency Tables and Code in HumanPen Start Project
Rigorous categorical data verification is essential across empirical science, whether constructing baseline Table 1 demographic profiles, analyzing subgroup treatment interactions under CONSORT reporting guidelines, or evaluating conversion lifts in A/B testing and experimentation workflows. However, verifying expected cell count rules across dozens of subgroup strata, reconciling discrepancies between Python and R contingency outputs, and formatting publication-standard three-line tables for journals often consumes extensive programming time that invites transcription errors. In HumanPen Start Project, researchers and analysts can structure, execute, and verify these categorical analyses end-to-end within an audited computational framework.
Attach your data and papers, describe what you need, approve the plan before work starts, and get the reviewed report, charts, and code ready to preview online or download. The platform supports structured datasets, statistical plans, and draft manuscripts in Excel, CSV, Word, PDF, or zip archives up to 2 GB total. Analyses originally planned in SPSS or Stata are performed within an isolated sandbox environment running native Python or R, allowing automatic cross-validation between SciPy routines and R `stats` functions to confirm continuity correction parameters, conditional odds ratios, and adjusted Cramér's V metrics. External proprietary datasets from platforms such as CNKI or Wind must be exported prior to uploading, and GPU training is not supported. Users can request revisions directly within the project interface, maintaining past version history, while project data is encrypted in transit and retained for 6 months (180 days) following activity with a 3-day reminder and anytime deletion. Researchers can also inspect live public example projects without signing in to evaluate delivered tables, figures, and execution code before initiating their own project.
This dual-language statistical verification architecture is reflected in the live public International Stroke Trial (IST) secondary analysis project (explore the IST public project). Analyzing raw clinical records from 19,435 acute stroke patients across a 3×2 factorial design testing aspirin and subcutaneous heparin, the analysis reproduces the 1997 Lancet event distributions (62.2% vs 63.5% 6-month death or dependency; unadjusted `p = 0.072`, prespecified covariate-adjusted odds ratio `OR = 0.93`, `95% CI 0.87–0.99`). The project deliverables include the complete `.docx` Statistical Analysis Report (`IST_统计分析报告_SAR.docx`), 22 clinical summary tables, 300 dpi CONSORT and subgroup forest figures, and the independent R cross-verification script (`check_with_R.R`).
All generated statistical tables, code scripts, and analytical summaries serve as reproducible methodological and educational scaffolds; authors must inspect code logic, verify clinical data against primary case records, supply personal institutional disclosures, and comply with journal publication guidelines.
Frequently Asked Questions
Can I run Pearson's chi-square test if an observed cell count is zero? Yes, provided that the theoretical expected cell count for that cell is at least 5 (`E_ij >= 5`) and Cochran's conditions are satisfied across the entire table. The validity of the asymptotic chi-square approximation depends entirely on theoretical expected counts under the null hypothesis of independence, not on the realized sample counts. An observed frequency of zero in a sample with an expected count of 6.2 does not violate the mathematical assumptions of Pearson's test, although investigators often report Fisher's exact test alongside chi-square as a sensitivity analysis when zero counts occur.
Why does my chi-square test p-value in R differ from Python SciPy for the exact same 2x2 table? This discrepancy almost always stems from Yates' continuity correction. While both R `stats::chisq.test()` and SciPy `scipy.stats.chi2_contingency()` enable Yates' correction by default for `2 × 2` tables, discrepancies emerge if an analyst passes `correct = FALSE` in R while leaving Python at `correction=True`, or compares `chi2_contingency()` against an uncorrected two-proportion z-test. In addition, `scipy.stats.contingency.association(..., method='cramer')` defaults to uncorrected chi-square (`correction=False`). To ensure cross-language alignment, explicitly declare `correction=False` or `correction=True` in both environments.
When should I report Relative Risk instead of an Odds Ratio for 2x2 contingency tables? Report Relative Risk (RR) in prospective randomized controlled trials and cohort studies where the total population at risk is monitored and true event incidence can be observed. While the Odds Ratio (OR) is mathematically symmetrical and functions across both prospective and retrospective case-control designs, it substantially overstates effect magnitude when the outcome is common (incidence greater than 10%). In retrospective case-control studies where baseline population incidence cannot be calculated, the Odds Ratio remains the required effect size metric.
What is the difference between Cramér's V and Tschuprow's T in rectangular tables? Both statistics measure nominal association based on the chi-square statistic, but they normalize using different denominator degrees of freedom. Cramér's `V` divides by `min(r - 1, c - 1)`, which enables the coefficient to span the full theoretical range from 0.0 to 1.0 regardless of whether the table is square (`2 × 2`, `3 × 3`) or rectangular (`2 × 4`, `3 × 5`). Tschuprow's `T` divides by `sqrt((r - 1)(c - 1))`; in non-square rectangular tables, Tschuprow's `T` cannot reach 1.0 even under complete deterministic association. Consequently, Cramér's `V` is preferred for standard contingency table reporting.
Sources
- Cochran (1954, Biometrics) — Some Methods for Strengthening the Common Chi-Square Tests — Foundational methodological paper establishing expected cell count rules and validity criteria for the chi-square approximation.
- R Core Team — R stats::fisher.test Official Documentation — Reference manual for Fisher's exact test, Cochran hybrid parameters, and conditional MLE odds ratios.
- SciPy Community — scipy.stats.chi2_contingency Reference Manual — Official documentation for chi-square contingency table tests and Yates' continuity correction defaults.
- R Core Team — R stats::chisq.test Official Documentation — Reference manual for Pearson's chi-square test, Yates' continuity correction, and Monte Carlo p-value simulation.
- SciPy Community — scipy.stats.contingency.odds_ratio Documentation — Technical manual for computing exact conditional MLE and sample odds ratios with confidence intervals.
- Statsmodels Developers — statsmodels.stats.contingency_tables Documentation — Implementation guide for 2x2 contingency tables, Haldane-Anscombe zero-shifts, and McNemar tests.
- CRAN effectsize Package — Indices of Nominal Association (Cramer's V & Phi) — Technical documentation for Cramer's V, Bergsma small-sample bias corrections, and confidence intervals.
- SciPy GitHub Repository — scipy.stats.contingency Source Code — Source implementation for Cramer's V, Tschuprow's T, and Pearson contingency coefficients.
Primary-source documentation, journal articles, and package API parameters verified against live endpoints and official package releases on November 22, 2026. Consult individual target journal statistical guidelines for specific contingency table presentation standards and confidence interval reporting conventions.
KEEP READING
Welch's vs Student's t-Test: Levene Trap, Python vs R, and Effect Sizes
13 min read
Tools & workflowRepeated-Measures ANOVA Sphericity Guide: Mauchly's W, GG vs HF, and LMM
12 min read
Tools & workflowMann-Whitney U & Kruskal-Wallis with Dunn's Post-Hoc Test: Nonparametric Guide
13 min read