CAssociation · contingency.chisq
χ² test of independence
Are two categorical variables associated?
Pearson χ² on the contingency table (no continuity correction) with expected counts, adjusted residuals, the likelihood-ratio G statistic and bias-corrected Cramér's V; a seeded Monte Carlo p-value for sparse tables; Fisher's exact test and the conditional odds ratio for 2×2 tables. Choose any member of the Cressie–Read power-divergence family as the test statistic, frame the question as independence or homogeneity, and add sampling weights, clusters and strata for the Rao–Scott design-based correction.
A real result
Example “Two by two fisher”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
χ²(1, N = 4526) = 92.21, p < .001, V = .14
- χ²
- 92.205
- df
- 1
- p (χ² test)
- < .001
- G (likelihood ratio)
- 93.449
- p (G)
- < .001
- Fisher's exact p
- < .001
Effect size
- Cramér's V (bias-corrected) 0.1420 · small
- Cramér's V 0.1427
- Odds ratio (conditional MLE) 1.841 95% CI [1.621, 2.091]
Plots
Cells show counts; color is the adjusted residual (|z| > 1.96 stands out).
View data
| admit | count | gender | adjusted residual |
|---|---|---|---|
| Admitted | 1198 | Male | 9.602 |
| Rejected | 1493 | Male | −9.602 |
| Admitted | 557 | Female | −9.602 |
| Rejected | 1278 | Female | 9.602 |
Assumptions
- Expected counts ≥ 5 — Smallest expected count 711.54; 0 of 4 cells below 5.
Observed counts
| gender \ admit | Admitted | Rejected | Total |
|---|---|---|---|
| Male | 1,198 | 1,493 | 2,691 |
| Female | 557 | 1,278 | 1,835 |
Adjusted standardized residuals (|z| > 1.96 stands out)
| gender \ admit | Admitted | Rejected |
|---|---|---|
| Male | 9.602 | −9.602 |
| Female | −9.602 | 9.602 |
- Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals.
χ²(1, N = 4526) = 92.21, p < .001, V = .14
- χ²
- 92.205
- df
- 1
- p (χ² test)
- < .001
- G (likelihood ratio)
- 93.449
- p (G)
- < .001
- Fisher's exact p
- < .001
Effect size
- Cramér's V (bias-corrected) 0.1420 · small
- Cramér's V 0.1427
- Odds ratio (conditional MLE) 1.841 95% CI [1.621, 2.091]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Expected counts ≥ 5 — Smallest expected count 711.54; 0 of 4 cells below 5.
Observed counts
| gender \ admit | Admitted | Rejected | Total |
|---|---|---|---|
| Male | 1,198 | 1,493 | 2,691 |
| Female | 557 | 1,278 | 1,835 |
Adjusted standardized residuals (|z| > 1.96 stands out)
| gender \ admit | Admitted | Rejected |
|---|---|---|
| Male | 9.602 | −9.602 |
| Female | −9.602 | 9.602 |
- Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals.
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
- Two by two fisherucb_admissions · cols: admit · rows: gender
- Four by fourhair_eye · cols: eye · rows: hair
- Sparse cellsmtcars · cols: manual · rows: cyl_f
- Sparse monte carlomtcars · cols: am_f · rows: cyl_f
- Homogeneity guidee_guide_2x2 · cols: outcome · rows: arm
- Cressie readhair_eye · cols: eye · rows: hair
- Freeman tukey lambdae_guide_strata · cols: outcome · rows: centre
- Neyman monte carloe_guide_strata · cols: outcome · rows: centre
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Two groups, binary outcome: two-proportion z, Fisher's exact · Statistics Guide · B — Compare groups
- 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
- Two independent proportions · Statistics Guide · E — Compare proportions / frequencies
- More than two groups: χ² independence · Statistics Guide · E — Compare proportions / frequencies
- Expected counts ≥ 5? otherwise exact tests · Statistics Guide · E — Compare proportions / frequencies
- Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
- Regression (linear, GLM), ANOVA, t-tests, chi-square · DS & ML Decision Guide · Explain — why is it happening?
What you need
- Rowscategorical / boolean · 1 column · 2–30 levels
- The variable whose levels form the table's rows.
- Columnscategorical / boolean · 1 column · 2–30 levels
- The variable whose levels form the table's columns.
- Sampling weightsnumeric · 0–1 column
- Survey weights (inverse selection probabilities). Setting weights, clusters or strata switches to the Rao–Scott test.
- Clusters (PSUs)categorical / numeric · 0–1 column
- Primary sampling unit of each row (school, household, village). Clusters are nested within strata.
- Design stratacategorical / numeric · 0–1 column
- The sampling strata, if the sample was drawn separately within each. Every stratum needs at least two clusters.
Choices you make
hypothesis
- Questiondefault independence
The arithmetic is the same; this changes the hypothesis and the wording of the result.
- Independence (one sample)(default) — One sample classified by two variables: are the variables related?
- Homogeneity (groups compared) — Separate samples (the rows are groups): is the distribution of the column variable the same in every group?
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
- Monte Carlo p-valuedefault off
Permutation (fixed margins) p-value with a seeded stream, identical in Python and R. Use when expected counts are small.
statistics
- Test statisticdefault pearson
Members of the Cressie–Read power-divergence family. All have the same χ² reference distribution; they weigh small and large cells differently.
- Pearson χ² (λ = 1)(default) — The usual χ² statistic.
- Likelihood-ratio G² (λ = 0) — Twice the log-likelihood ratio; adds over nested tables.
- Cressie–Read (λ = 2/3 or your λ) — Cressie and Read's recommended compromise, closest to χ² in small samples.
- Freeman–Tukey (λ = −½) — 4 Σ (√O − √E)² in the limit; least affected by large cells.
- Modified G² (λ = −1) — Undefined when a cell is empty.
- Neyman χ² (λ = −2) — Σ (O − E)² / O; undefined when a cell is empty.
- λ (Cressie–Read)default 0.6666666666666666
1 gives Pearson's χ², 0 the G² statistic, −½ Freeman–Tukey, −2 Neyman.
- Fisher's exact test (2 × 2 tables)default on
Also report Fisher's exact test for 2 × 2 tables (useful when expected counts are small).
options
- Simulationsdefault 5000
Number of simulated tables behind the Monte Carlo p-value. More is more precise but slower.
- Rao–Scott correctiondefault second_order
Used when sampling weights, clusters or strata are set.
- Second order (F test)(default) — Satterthwaite-adjusted F with the design's degrees of freedom; recommended (survey::svychisq's default).
- First order (χ²) — Divides χ² by the mean design effect; adequate when design effects are similar across cells.
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.
Expected counts ≥ 5
Cochran's rule; below 1 the χ² approximation fails — use an exact or Monte Carlo test.
- If violated → Monte Carlo (permutation) p-value — Simulating tables with the observed margins does not rely on the χ² approximation, so small expected counts are fine (Fisher's exact test is reported for 2 × 2 tables).
- If violated → Fisher–Freeman–Halton exact test — Exact (or shared-RNG Monte Carlo) p-value for any R × C table, with no expected-count requirement.
Each row counted onceNot checked from data: state why it holds
Sampling design accounted for
With weights, clusters or strata the p-value comes from the Rao–Scott design-based correction.
What it reports
- Tests: Association between the two variables
- Tests: Association (Fisher's exact test)
- chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- df
- How much independent information is left to estimate variability after fitting the model.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- n
- How many independent units the analysis used; it sets precision and power.
- cramers_v
- Association strength in a contingency table, from 0 (none) to 1 (perfect).
- cramers_v_corrected
- 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.
- cells_below_5
- The counts a contingency table would have if the variables were independent; χ² needs them not too small.
- g
- The mean difference divided by the pooled SD, multiplied by a small-sample correction J that removes Cohen's d's upward bias.
- g_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- chi2_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- mc_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- fisher_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- odds_ratio
- How many times higher the odds of an event are in one group than another; 1 means no difference.
- or_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- or_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- nr
- Number of row categories in the table that was tested.
- nc
- Number of column categories in the table that was tested.
- pd_stat
- One family of goodness-of-fit statistics indexed by λ — Pearson's χ² (λ = 1), G² (λ = 0), Freeman–Tukey (−½), Neyman (−2).
- pd_lambda
- One family of goodness-of-fit statistics indexed by λ — Pearson's χ² (λ = 1), G² (λ = 0), Freeman–Tukey (−½), Neyman (−2).
- pd_p
- One family of goodness-of-fit statistics indexed by λ — Pearson's χ² (λ = 1), G² (λ = 0), Freeman–Tukey (−½), Neyman (−2).
- statistic_label
- Name of the test behind the p-value: χ², a power-divergence member such as Cressie–Read, or Rao–Scott; Monte Carlo is noted.
- rs_f
- Adjusts χ² for a complex sample (weights, clusters, strata) by dividing by the design effect, so p-values are not too small.
- rs_ndf
- How much independent information is left to estimate variability after fitting the model.
- rs_ddf
- How much independent information is left to estimate variability after fitting the model.
- rs_p
- Adjusts χ² for a complex sample (weights, clusters, strata) by dividing by the design effect, so p-values are not too small.
- rs_x2_first
- Adjusts χ² for a complex sample (weights, clusters, strata) by dividing by the design effect, so p-values are not too small.
- rs_p_first
- Adjusts χ² for a complex sample (weights, clusters, strata) by dividing by the design effect, so p-values are not too small.
- deff_mean
- How much the sampling design inflates a variance compared with a simple random sample of the same size.
- n_psu
- The first unit drawn in a multistage sample (a school, a household, a village); rows in the same PSU tend to be alike.
- n_strata
- How many independent units the analysis used; it sets precision and power.
Per group, level or term: stdres[<row>|<col>], expected[<row>|<col>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- The conditional-MLE odds ratio and its interval come from root finding: scipy's odds_ratio in Python, cs_fisher_or solved to 1e-12 in R. stats::fisher.test stops much earlier (about 1e-4), so it can differ from these: median 1.7e-5 relative on the odds ratio and 6e-5 on a limit across 400 tables, and much more on extreme tables, where it is the inaccurate side. On (2, 1500, 1500, 5) it reports 0, and the true root is 5.1148e-6.
- Monte Carlo p-values permute with the shared Wichmann–Hill stream (codesplash.stats.rng ≡ cs_rng), so both engines simulate the same tables.
- Power-divergence statistics and the Rao–Scott correction are codesplash twins in both engines (cs_power_divergence, cs_rao_scott); the Rao–Scott F, degrees of freedom and p match survey::svychisq to ≈1e-12 (the survey package is a test oracle, not a dependency).
- survey::svychisq(statistic = 'Chisq') prints the unadjusted X² beside its first-order p-value; rs_x2_first is the adjusted statistic X²·df/tr(Δ) that p refers to.
The exact script CodeSplash ran for example “Two by two fisher” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# χ² test of independence
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.chisq 1.3.1 · spec 87ec80489961c7f6
# Dataset: ucb_admissions (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 proportions as csp # Monte Carlo p (twin of codesplashr::cs_chisq_mc)
from codesplash.stats import proportions_ext as csx # power-divergence family (twins of cs_power_divergence …)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ucb_admissions.parquet", columns=["gender", "admit"])
n_input = len(df)
df["gender"] = pd.Categorical(df["gender"], categories=["Male", "Female"]) # stored level order
df["admit"] = pd.Categorical(df["admit"], categories=["Admitted", "Rejected"]) # stored level order
df = df.dropna(subset=["gender", "admit"]) # listwise deletion over the analysis columns
df["gender"] = df["gender"].cat.remove_unused_categories()
df["admit"] = df["admit"].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, ["gender", "admit"]) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
a, b = "gender", "admit"
table = pd.crosstab(df[a], df[b], dropna=False) # stored level order
observed = table.to_numpy(dtype=float)
row_levels = [str(v) for v in table.index]
col_levels = [str(v) for v in table.columns]
nr, nc = observed.shape
n = float(observed.sum())
if nr < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=a, min=2, k=nr)
if nc < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=b, min=2, k=nc)
conf = 0.95
want_fisher = True
use_mc = False
framing = "independence" # independence (one sample, two variables) or homogeneity (groups compared)
statistic = "pearson"
lam = csx.pd_lambda(statistic, 0.6666666666666666) # Cressie–Read λ (1 = Pearson, 0 = G²)
chi2, chi2_p, dof, expected = stats.chi2_contingency(observed, correction=False) # pinned: no Yates correction
chi2, chi2_p = float(chi2), float(chi2_p)
pos = observed > 0
g = float(2 * np.sum(observed[pos] * np.log(observed[pos] / expected[pos]))) # likelihood-ratio G
g_p = float(stats.chi2.sf(g, dof))
# Power-divergence statistic chosen in the options (Cressie & Read 1984); Pearson's is χ² itself
pd_stat = chi2 if statistic == "pearson" else csx.power_divergence(observed, expected, lam)
pd_p = chi2_p if statistic == "pearson" else (float(stats.chi2.sf(pd_stat, dof)) if math.isfinite(pd_stat) else None)
if pd_p is None:
warnings.append(f"The {csx.PD_LABEL[statistic]} statistic is undefined when a cell is empty; Pearson's χ² is used instead.")
statistic, lam, pd_stat, pd_p = "pearson", 1.0, chi2, chi2_p
rows_code = np.array([row_levels.index(str(x)) for x in df[a]])
cols_code = np.array([col_levels.index(str(x)) for x in df[b]])
mc_p = None
if use_mc: # permutation p-value with fixed margins (seeded; identical in R)
if statistic == "pearson":
mc_p = csp.chisq_mc(rows_code, cols_code, nr, nc, expected, int(5000), seed=42)
else:
mc_p = csx.pd_chisq_mc(rows_code, cols_code, nr, nc, expected, int(5000), 42, lam)
rs = None
if rs is not None:
p = rs["p_f"] if correction == "second_order" else rs["p_first"]
label = "Rao–Scott F (second order)" if correction == "second_order" else "Rao–Scott χ² (first order)"
else:
p = mc_p if use_mc else pd_p
label = ("χ² test" if statistic == "pearson" else f"{csx.PD_LABEL[statistic]} test") + (" (Monte Carlo)" if use_mc else "")
row_p = observed.sum(axis=1, keepdims=True) / n
col_p = observed.sum(axis=0, keepdims=True) / n
stdres = (observed - expected) / np.sqrt(expected * (1 - row_p) * (1 - col_p)) # adjusted residuals (R's $stdres)
cramers_v = float(np.sqrt(chi2 / (n * (min(nr, nc) - 1))))
# Bias-corrected Cramér's V (Bergsma 2013)
phi2c = max(0.0, chi2 / n - (nr - 1) * (nc - 1) / (n - 1))
rc, cc = nr - (nr - 1) ** 2 / (n - 1), nc - (nc - 1) ** 2 / (n - 1)
cramers_v_corrected = float(np.sqrt(phi2c / min(rc - 1, cc - 1)))
min_expected = float(expected.min())
cells_below_5 = int((expected < 5).sum())
fisher = None
if want_fisher and (nr, nc) == (2, 2):
fisher_p = float(stats.fisher_exact(observed)[1])
orr = stats.contingency.odds_ratio(observed.astype(int), kind="conditional") # conditional MLE (R's fisher.test)
or_ci = orr.confidence_interval(confidence_level=conf)
fisher = {"p": fisher_p, "or": float(orr.statistic), "low": float(or_ci.low), "high": float(or_ci.high)}
# %% Assumptions
warnings = list(warnings)
if use_mc or rs is not None:
status = "info"
elif min_expected < 1:
status = "fail"
elif cells_below_5:
status = "warn"
else:
status = "pass"
if rs is not None:
detail = f"The design-based test does not rely on the unweighted expected counts (smallest {min_expected:.2f})."
elif use_mc:
detail = f"Monte Carlo p-value ({int(5000):,} permutations, seed 42); smallest expected count {min_expected:.2f}."
else:
detail = (
f"Smallest expected count {min_expected:.2f}; {cells_below_5} of {nr * nc} cells below 5."
+ (" Use Fisher's exact test or the Monte Carlo p-value." if status != "pass" else "")
)
assumptions = [{"key": "expected_counts", "label": "Expected counts ≥ 5", "status": status, "detail": detail}]
if rs is not None:
assumptions.append({"key": "survey_design", "label": "Sampling design accounted for", "status": "pass",
"detail": f"Rao–Scott correction over {rs['n_psu']} primary sampling units in {rs['n_strata']} strata; "
f"mean design effect {rs['deff_mean']:.2f}."})
# %% Result
alpha = 1 - conf
size = magnitude(cramers_v_corrected, (0.1 / np.sqrt(min(nr, nc) - 1), 0.3 / np.sqrt(min(nr, nc) - 1), 0.5 / np.sqrt(min(nr, nc) - 1)))
if framing == "homogeneity":
significance = (
f"The distribution of {b} differs between the groups of {a} ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with the same distribution of {b} in every group of {a} ({cs.fmt_p(p)})."
)
test_name = "homogeneity"
else:
significance = (
f"{a} and {b} are associated ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with independence of {a} and {b} ({cs.fmt_p(p)})."
)
test_name = "independence"
summary = f"{label} of {test_name} on a {nr} × {nc} table of {int(n)} rows. {significance} The association is {size} (bias-corrected Cramér's V = {cramers_v_corrected:.2f})."
if fisher:
summary += f" Fisher's exact test: {cs.fmt_p(fisher['p'])}, conditional odds ratio {fisher['or']:.2f}."
values = {"chi2": chi2, "df": float(dof), "p": p, "n": int(n), "cramers_v": cramers_v, "cramers_v_corrected": cramers_v_corrected,
"min_expected": min_expected, "cells_below_5": cells_below_5, "g": g, "g_p": g_p, "chi2_p": chi2_p, "mc_p": mc_p,
"fisher_p": fisher["p"] if fisher else None, "odds_ratio": fisher["or"] if fisher else None,
"or_ci_low": fisher["low"] if fisher else None, "or_ci_high": fisher["high"] if fisher else None, "nr": nr, "nc": nc,
"pd_stat": pd_stat, "pd_lambda": lam, "pd_p": pd_p, "statistic_label": label,
"rs_f": rs["f"] if rs else None, "rs_ndf": rs["ndf"] if rs else None, "rs_ddf": rs["ddf"] if rs else None,
"rs_p": rs["p_f"] if rs else None, "rs_x2_first": rs["x2_first"] if rs else None, "rs_p_first": rs["p_first"] if rs else None,
"deff_mean": rs["deff_mean"] if rs else None, "n_psu": rs["n_psu"] if rs else None, "n_strata": rs["n_strata"] if rs else None}
for i, rl in enumerate(row_levels):
for j, cl in enumerate(col_levels):
values[f"stdres[{rl}|{cl}]"] = float(stdres[i, j])
values[f"expected[{rl}|{cl}]"] = float(expected[i, j])
columns = [{"key": "row", "label": f"{a} \\ {b}", "type": "string"}] + [
{"key": f"c{j}", "label": cl, "type": "integer"} for j, cl in enumerate(col_levels)] + [{"key": "total", "label": "Total", "type": "integer"}]
counts = [{"row": rl, **{f"c{j}": int(observed[i, j]) for j in range(nc)}, "total": int(observed[i].sum())} for i, rl in enumerate(row_levels)]
residual_rows = [{"row": rl, **{f"c{j}": float(stdres[i, j]) for j in range(nc)}} for i, rl in enumerate(row_levels)]
effect_sizes = [
{"key": "cramers_v_corrected", "label": "Cramér's V (bias-corrected)", "value": cramers_v_corrected, "method": "Bergsma (2013)",
"magnitude": size, "ruleSet": "Cohen (1988), w / √(min(r, c) − 1)"},
{"key": "cramers_v", "label": "Cramér's V", "value": cramers_v, "method": "√(χ² / (n (min(r, c) − 1)))"},
]
if fisher:
effect_sizes.append({"key": "odds_ratio", "label": "Odds ratio (conditional MLE)", "value": fisher["or"], "ciLow": fisher["low"],
"ciHigh": fisher["high"], "ciLevel": conf, "method": "Fisher's exact test"})
cells = [(rl, cl, float(stdres[i, j]), int(observed[i, j])) for i, rl in enumerate(row_levels) for j, cl in enumerate(col_levels)]
cs.publish({
"method": "contingency.chisq",
"methodVersion": "1.3.1",
"title": "χ² test of homogeneity" if framing == "homogeneity" else "χ² test of independence",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(n),
"summary": summary,
"apa": (
f"Rao–Scott F({cs.fmt_num(rs['ndf'])}, {cs.fmt_num(rs['ddf'])}) = {cs.fmt_num(rs['f'])}, {cs.fmt_p(p)}" if rs is not None and correction == "second_order"
else f"Rao–Scott χ²({dof}) = {cs.fmt_num(rs['x2_first'])}, {cs.fmt_p(p)}" if rs is not None
else f"χ²({dof}, N = {int(n)}) = {cs.fmt_num(chi2)}, {cs.fmt_p(p)}, V = {cs.fmt_num(cramers_v_corrected, leading_zero=False)}" if statistic == "pearson"
else f"{csx.PD_LABEL[statistic]} (λ = {cs.fmt_num(lam)})({dof}, N = {int(n)}) = {cs.fmt_num(pd_stat)}, {cs.fmt_p(p)}, V = {cs.fmt_num(cramers_v_corrected, leading_zero=False)}"
),
"statistics": [{"key": "chi2", "label": "χ²", "value": chi2}, {"key": "df", "label": "df", "value": dof},
{"key": "p", "label": f"p ({label})", "value": p, "format": "p"},
{"key": "g", "label": "G (likelihood ratio)", "value": g}, {"key": "g_p", "label": "p (G)", "value": g_p, "format": "p"}]
+ ([{"key": "pd_stat", "label": f"{csx.PD_LABEL[statistic]} (λ = {lam:.3g})", "value": pd_stat},
{"key": "pd_p", "label": f"p ({csx.PD_LABEL[statistic]})", "value": pd_p, "format": "p"}] if statistic not in ("pearson", "g") else [])
+ ([{"key": "rs_f", "label": "Rao–Scott F", "value": rs["f"]}, {"key": "rs_ndf", "label": "df (numerator)", "value": rs["ndf"]},
{"key": "rs_ddf", "label": "df (denominator)", "value": rs["ddf"]}, {"key": "rs_p", "label": "p (Rao–Scott F)", "value": rs["p_f"], "format": "p"},
{"key": "rs_x2_first", "label": "Rao–Scott χ² (first order)", "value": rs["x2_first"]},
{"key": "rs_p_first", "label": "p (first order)", "value": rs["p_first"], "format": "p"},
{"key": "deff_mean", "label": "Mean design effect", "value": rs["deff_mean"]}] if rs is not None else [])
+ ([{"key": "fisher_p", "label": "Fisher's exact p", "value": fisher["p"], "format": "p"}] if fisher else []),
"tables": [
{"key": "observed", "title": "Observed counts", "columns": columns, "rows": counts},
{"key": "stdres", "title": "Adjusted standardized residuals (|z| > 1.96 stands out)",
"columns": [{**c, "type": "number"} if c["key"].startswith("c") else c for c in columns[:-1]], "rows": residual_rows},
],
"effectSizes": effect_sizes,
"assumptions": assumptions,
"warnings": warnings,
"notes": ["Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals."]
+ (["Counts, χ², G, Cramér's V and the residuals describe the unweighted sample; the p-value is design-based (Rao–Scott)."] if rs is not None else []),
"charts": [cs.chart(
"residuals", "matrix-heatmap", f"Adjusted residuals: {a} × {b}",
{"row": cs.col(a, [c[0] for c in cells], levels=row_levels), "col": cs.col(b, [c[1] for c in cells], levels=col_levels),
"value": cs.col("adjusted residual", [c[2] for c in cells]), "label": cs.col("count", [str(c[3]) for c in cells])},
controls={"scale": "diverging"}, note="Cells show counts; color is the adjusted residual (|z| > 1.96 stands out).",
)],
"values": values,
})
The exact script CodeSplash ran for example “Two by two fisher” · R version 4.5.1 (2025-06-13)
# χ² test of independence
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.chisq 1.3.1 · spec 87ec80489961c7f6
# Dataset: ucb_admissions (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_fisher_or, cs_chisq_mc, cs_power_divergence (twins of codesplash.stats)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ucb_admissions.parquet", col_select = c("gender", "admit")))
n_input <- nrow(df)
df[["gender"]] <- factor(df[["gender"]], levels = c("Male", "Female")) # stored level order
df[["admit"]] <- factor(df[["admit"]], levels = c("Admitted", "Rejected")) # stored level order
df <- df[stats::complete.cases(df[c("gender", "admit")]), , 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("gender", "admit")) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
a <- "gender"
b <- "admit"
tab <- table(df[[a]], df[[b]]) # stored level order
row_levels <- rownames(tab)
col_levels <- colnames(tab)
nr <- nrow(tab)
nc <- ncol(tab)
n <- sum(tab)
if (nr < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = a, min = 2, k = nr)
if (nc < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = b, min = 2, k = nc)
conf <- 0.95
want_fisher <- TRUE
use_mc <- FALSE
framing <- "independence" # independence (one sample, two variables) or homogeneity (groups compared)
statistic <- "pearson"
lam <- cs_pd_lambda(statistic, 0.6666666666666666) # Cressie–Read lambda (1 = Pearson, 0 = G²)
pd_label <- c(pearson = "Pearson χ²", g = "likelihood-ratio G²", cressie_read = "Cressie–Read", freeman_tukey = "Freeman–Tukey",
mod_g = "modified G²", neyman = "Neyman χ²")
res <- suppressWarnings(chisq.test(tab, correct = FALSE)) # pinned: no Yates correction; expected counts checked below
chi2 <- unname(res$statistic)
dof <- unname(res$parameter)
chi2_p <- res$p.value
expected <- res$expected
pos <- tab > 0
g <- 2 * sum(tab[pos] * log(tab[pos] / expected[pos])) # likelihood-ratio G
g_p <- pchisq(g, dof, lower.tail = FALSE)
# Power-divergence statistic chosen in the options (Cressie & Read 1984); Pearson's is chi-square itself
pd_stat <- if (statistic == "pearson") chi2 else cs_power_divergence(tab, expected, lam)
pd_p <- if (statistic == "pearson") chi2_p else if (is.finite(pd_stat)) pchisq(pd_stat, dof, lower.tail = FALSE) else NULL
if (is.null(pd_p)) {
warnings <- c(warnings, sprintf("The %s statistic is undefined when a cell is empty; Pearson's χ² is used instead.", pd_label[[statistic]]))
statistic <- "pearson"; lam <- 1; pd_stat <- chi2; pd_p <- chi2_p
}
rows_code <- as.integer(df[[a]])
cols_code <- as.integer(df[[b]])
mc_p <- NULL
if (use_mc) { # permutation p-value with fixed margins (seeded; identical in Python)
mc_p <- if (statistic == "pearson") {
cs_chisq_mc(rows_code, cols_code, nr, nc, expected, 5000, seed = 42)
} else {
cs_pd_chisq_mc(rows_code, cols_code, nr, nc, expected, 5000, 42, lam)
}
}
rs <- NULL
if (!is.null(rs)) {
p <- if (correction == "second_order") rs$p_f else rs$p_first
label <- if (correction == "second_order") "Rao–Scott F (second order)" else "Rao–Scott χ² (first order)"
} else {
p <- if (use_mc) mc_p else pd_p
label <- paste0(if (statistic == "pearson") "χ² test" else paste(pd_label[[statistic]], "test"), if (use_mc) " (Monte Carlo)" else "")
}
stdres <- res$stdres # adjusted residuals
cramers_v <- sqrt(chi2 / (n * (min(nr, nc) - 1)))
# Bias-corrected Cramer's V (Bergsma 2013)
phi2c <- max(0, chi2 / n - (nr - 1) * (nc - 1) / (n - 1))
rc <- nr - (nr - 1)^2 / (n - 1)
cc <- nc - (nc - 1)^2 / (n - 1)
cramers_v_corrected <- sqrt(phi2c / min(rc - 1, cc - 1))
min_expected <- min(expected)
cells_below_5 <- sum(expected < 5)
fisher <- NULL
if (want_fisher && nr == 2 && nc == 2) {
ft <- fisher.test(tab, conf.level = conf)
fo <- cs_fisher_or(tab[1, 1], tab[1, 2], tab[2, 1], tab[2, 2], conf) # conditional MLE solved to 1e-12
fisher <- list(p = ft$p.value, or = fo$or, low = fo$low, high = fo$high)
}
# %% Assumptions
status <- if (use_mc || !is.null(rs)) "info" else if (min_expected < 1) "fail" else if (cells_below_5 > 0) "warn" else "pass"
detail <- if (!is.null(rs)) {
sprintf("The design-based test does not rely on the unweighted expected counts (smallest %.2f).", min_expected)
} else if (use_mc) {
sprintf("Monte Carlo p-value (%s permutations, seed 42); smallest expected count %.2f.", format(5000, big.mark = ","), min_expected)
} else {
paste0(sprintf("Smallest expected count %.2f; %d of %d cells below 5.", min_expected, cells_below_5, nr * nc),
if (status != "pass") " Use Fisher's exact test or the Monte Carlo p-value." else "")
}
assumptions <- list(list(key = "expected_counts", label = "Expected counts ≥ 5", status = status, detail = detail))
if (!is.null(rs)) {
assumptions[[2]] <- list(key = "survey_design", label = "Sampling design accounted for", status = "pass",
detail = sprintf("Rao–Scott correction over %d primary sampling units in %d strata; mean design effect %.2f.",
as.integer(rs$n_psu), as.integer(rs$n_strata), rs$deff_mean))
}
# %% Result
alpha <- 1 - conf
s <- sqrt(min(nr, nc) - 1)
size <- magnitude(cramers_v_corrected, c(0.1, 0.3, 0.5) / s)
if (framing == "homogeneity") {
significance <- if (p < alpha) {
sprintf("The distribution of %s differs between the groups of %s (%s).", b, a, cs_fmt_p(p))
} else {
sprintf("The data are compatible with the same distribution of %s in every group of %s (%s).", b, a, cs_fmt_p(p))
}
test_name <- "homogeneity"
} else {
significance <- if (p < alpha) {
sprintf("%s and %s are associated (%s).", a, b, cs_fmt_p(p))
} else {
sprintf("The data are compatible with independence of %s and %s (%s).", a, b, cs_fmt_p(p))
}
test_name <- "independence"
}
summary <- sprintf("%s of %s on a %d × %d table of %d rows. %s The association is %s (bias-corrected Cramér's V = %.2f).",
label, test_name, nr, nc, as.integer(n), significance, size, cramers_v_corrected)
if (!is.null(fisher)) summary <- paste(summary, sprintf("Fisher's exact test: %s, conditional odds ratio %.2f.", cs_fmt_p(fisher$p), fisher$or))
values <- list(chi2 = chi2, df = dof, p = p, n = n, cramers_v = cramers_v, cramers_v_corrected = cramers_v_corrected,
min_expected = min_expected, cells_below_5 = cells_below_5, g = g, g_p = g_p, chi2_p = chi2_p, mc_p = mc_p,
fisher_p = if (is.null(fisher)) NULL else fisher$p, odds_ratio = if (is.null(fisher)) NULL else fisher$or,
or_ci_low = if (is.null(fisher)) NULL else fisher$low, or_ci_high = if (is.null(fisher)) NULL else fisher$high, nr = nr, nc = nc,
pd_stat = pd_stat, pd_lambda = lam, pd_p = pd_p, statistic_label = label,
rs_f = rs$f, rs_ndf = rs$ndf, rs_ddf = rs$ddf, rs_p = rs$p_f, rs_x2_first = rs$x2_first, rs_p_first = rs$p_first,
deff_mean = rs$deff_mean, n_psu = rs$n_psu, n_strata = rs$n_strata)
for (i in seq_len(nr)) {
for (j in seq_len(nc)) {
values[[sprintf("stdres[%s|%s]", row_levels[i], col_levels[j])]] <- stdres[i, j]
values[[sprintf("expected[%s|%s]", row_levels[i], col_levels[j])]] <- expected[i, j]
}
}
count_cols <- lapply(seq_len(nc), function(j) list(key = sprintf("c%d", j - 1), label = col_levels[j], type = "integer"))
columns <- c(list(list(key = "row", label = paste(a, "\\", b), type = "string")), count_cols, list(list(key = "total", label = "Total", type = "integer")))
counts <- lapply(seq_len(nr), function(i) {
c(list(row = row_levels[i]), stats::setNames(as.list(as.integer(tab[i, ])), sprintf("c%d", seq_len(nc) - 1)), list(total = as.integer(sum(tab[i, ]))))
})
residual_rows <- lapply(seq_len(nr), function(i) c(list(row = row_levels[i]), stats::setNames(as.list(unname(stdres[i, ])), sprintf("c%d", seq_len(nc) - 1))))
residual_cols <- c(list(list(key = "row", label = paste(a, "\\", b), type = "string")),
lapply(count_cols, function(cl) { cl$type <- "number"; cl }))
effect_sizes <- list(
list(key = "cramers_v_corrected", label = "Cramér's V (bias-corrected)", value = cramers_v_corrected, method = "Bergsma (2013)",
magnitude = size, ruleSet = "Cohen (1988), w / √(min(r, c) − 1)"),
list(key = "cramers_v", label = "Cramér's V", value = cramers_v, method = "√(χ² / (n (min(r, c) − 1)))")
)
if (!is.null(fisher)) {
effect_sizes[[3]] <- list(key = "odds_ratio", label = "Odds ratio (conditional MLE)", value = fisher$or, ciLow = fisher$low,
ciHigh = fisher$high, ciLevel = conf, method = "Fisher's exact test")
}
cell_row <- rep(row_levels, each = nc)
cell_col <- rep(col_levels, times = nr)
cs_publish(list(
method = "contingency.chisq",
methodVersion = "1.3.1",
title = if (framing == "homogeneity") "χ² test of homogeneity" else "χ² test of independence",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = if (!is.null(rs) && correction == "second_order") {
sprintf("Rao–Scott F(%s, %s) = %s, %s", cs_fmt_num(rs$ndf), cs_fmt_num(rs$ddf), cs_fmt_num(rs$f), cs_fmt_p(p))
} else if (!is.null(rs)) {
sprintf("Rao–Scott χ²(%d) = %s, %s", as.integer(dof), cs_fmt_num(rs$x2_first), cs_fmt_p(p))
} else if (statistic == "pearson") {
sprintf("χ²(%d, N = %d) = %s, %s, V = %s", dof, as.integer(n), cs_fmt_num(chi2), cs_fmt_p(p), cs_fmt_num(cramers_v_corrected, leading_zero = FALSE))
} else {
sprintf("%s (λ = %s)(%d, N = %d) = %s, %s, V = %s", pd_label[[statistic]], cs_fmt_num(lam), as.integer(dof), as.integer(n), cs_fmt_num(pd_stat),
cs_fmt_p(p), cs_fmt_num(cramers_v_corrected, leading_zero = FALSE))
},
statistics = c(list(list(key = "chi2", label = "χ²", value = chi2), list(key = "df", label = "df", value = dof),
list(key = "p", label = sprintf("p (%s)", label), value = p, format = "p"),
list(key = "g", label = "G (likelihood ratio)", value = g), list(key = "g_p", label = "p (G)", value = g_p, format = "p")),
if (!statistic %in% c("pearson", "g")) list(
list(key = "pd_stat", label = sprintf("%s (λ = %s)", pd_label[[statistic]], format(signif(lam, 3))), value = pd_stat),
list(key = "pd_p", label = sprintf("p (%s)", pd_label[[statistic]]), value = pd_p, format = "p")),
if (!is.null(rs)) list(
list(key = "rs_f", label = "Rao–Scott F", value = rs$f), list(key = "rs_ndf", label = "df (numerator)", value = rs$ndf),
list(key = "rs_ddf", label = "df (denominator)", value = rs$ddf), list(key = "rs_p", label = "p (Rao–Scott F)", value = rs$p_f, format = "p"),
list(key = "rs_x2_first", label = "Rao–Scott χ² (first order)", value = rs$x2_first),
list(key = "rs_p_first", label = "p (first order)", value = rs$p_first, format = "p"),
list(key = "deff_mean", label = "Mean design effect", value = rs$deff_mean)),
if (!is.null(fisher)) list(list(key = "fisher_p", label = "Fisher's exact p", value = fisher$p, format = "p"))),
tables = list(
list(key = "observed", title = "Observed counts", columns = columns, rows = counts),
list(key = "stdres", title = "Adjusted standardized residuals (|z| > 1.96 stands out)", columns = residual_cols, rows = residual_rows)
),
effectSizes = effect_sizes,
assumptions = assumptions,
warnings = warnings,
notes = c(list("Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals."),
if (!is.null(rs)) list("Counts, χ², G, Cramér's V and the residuals describe the unweighted sample; the p-value is design-based (Rao–Scott).")),
charts = list(cs_chart(
"residuals", "matrix-heatmap", sprintf("Adjusted residuals: %s × %s", a, b),
list(row = cs_col(a, cell_row, levels = row_levels), col = cs_col(b, cell_col, levels = col_levels),
value = cs_col("adjusted residual", as.numeric(t(stdres))), label = cs_col("count", as.character(as.integer(t(tab))))),
controls = list(scale = "diverging"), note = "Cells show counts; color is the adjusted residual (|z| > 1.96 stands out)."
)),
values = values
))
Sources
- Agresti, A. (2013). Categorical Data Analysis (3rd ed.). Wiley.
- Bergsma, W. (2013). A bias-correction for Cramér's V and Tschuprow's T. Journal of the Korean Statistical Society, 42, 323–328.
- Hope, A. C. A. (1968). A simplified Monte Carlo significance test procedure. JRSS B, 30, 582–598.
- Cressie, N., & Read, T. R. C. (1984). Multinomial goodness-of-fit tests. JRSS B, 46, 440–464.
- Rao, J. N. K., & Scott, A. J. (1984). On chi-squared tests for multiway contingency tables with cell proportions estimated from survey data. Annals of Statistics, 12, 46–60.
- Lumley, T. (2010). Complex Surveys: A Guide to Analysis Using R. Wiley, §6.2.
From the CodeSplash method registry · contingency.chisq v1.3.1.