Skip to content

Two categories: Cramér's V, phi and odds ratios

A chi-square test says whether two categorical variables are related. Cramér's V and the odds ratio say how strongly.

Applied ~10 min9 steps

What runs in CodeSplash

You will be able to

  • Separate "is there an association?" from "how strong is it?"
  • Compute Cramér's V from a chi-square statistic
  • Read an odds ratio and its interval for a two-by-two table

Read first

01

Hair and eye color

Read

Are hair color and eye color related? A classic survey of 592 students sorted people into four hair colors and four eye colors.

If the two were independent, each cell's expected count would follow from its row and column totals alone. The χ² statisticChi-square statisticA sum of squared, scaled differences between observed and expected counts or estimates. adds up how far the observed counts are from those expectations:

χ2=∑cells(O−E)2E\chi^2 = \sum_{\text{cells}} \frac{(O - E)^2}{E}
02

See where the χ² comes from

Explore

EExplorable · Observed against expected

How does a chi-square test turn a table of counts into one number?

What will the p-value be for this table?

0.50
How sure?
22
15
10
14
18
18
ABC
Row 1
22
expected 17.4
residual 1.09
15
expected 16.0
residual −0.25
10
expected 13.6
residual −0.97
Row 2
14
expected 18.6
residual −1.06
18
expected 17.0
residual 0.24
18
expected 14.4
residual 0.94

Shading shows how far each cell sits from its expected count. Residuals above about 2 stand out.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Change the counts in one cell and watch which cells contribute most to χ2\chi^2. Large contributions show you where the association lives, and that's usually more interesting than the total.

03

The test doesn't measure strength

Read

Here χ2\chi^2(9) = 138.3, p < .001. Compatible with independence? No.

But χ2\chi^2 grows with the sample size: double every count and it doubles too. To report strength you need a measure that doesn't grow. Cramér's VCramér's VAssociation strength in a contingency table, from 0 (none) to 1 (perfect). rescales χ2\chi^2 to run from 0 to 1:

V=χ2n min⁡(r−1, c−1)V = \sqrt{\frac{\chi^2}{n \,\min(r-1,\, c-1)}}
04

Predict V

Predict

Predict first

Use the formula with the χ2\chi^2 and nn above. Both variables have four levels, so the minimum is 3. Roughly what is V?

Make your guess between 0 and 1 Cramér's V, then reveal.

Reveal

V = 0.279, a moderate association. CodeSplash also gives a bias-corrected value, 0.270, which is the better estimate in small tables.

05

Two-by-two tables get an odds ratio

Read

In a 2×2 table, V is the absolute value of the phi coefficientPhi coefficientThe correlation for a 2 × 2 table., and there's a more direct effect size: the odds ratioOdds ratioHow many times higher the odds of an event are in one group than another; 1 means no difference..

Berkeley's 1973 graduate admissions, 4,526 applications: the odds of admission for men were 1.84 times the odds for women, 95% CI 1.62 to 2.09.

The same data split by department tell a different story. You'll meet that in the lesson on confounding.

06

Read the card

In the app
χ² test of independenceRecorded · Python and R agreeRecorded 2026-11-25 · 39 values compared · largest relative difference 1.9e-12
R

χ²(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

Adjusted residuals: gender × admitWhat do the values of a square or rectangular result matrix look like at a glance?

Cells show counts; color is the adjusted residual (|z| > 1.96 stands out).

View data
admitcountgenderadjusted residual
Admitted1198Male9.602
Rejected1493Male−9.602
Admitted557Female−9.602
Rejected1278Female9.602

Assumptions

  • Expected counts ≥ 5 — Smallest expected count 711.54; 0 of 4 cells below 5.

Observed counts

gender \ admitAdmittedRejectedTotal
Male1,1981,4932,691
Female5571,2781,835

Adjusted standardized residuals (|z| > 1.96 stands out)

gender \ admitAdmittedRejected
Male9.602−9.602
Female−9.6029.602
  • Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals.
The exact R script · R 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
))
Python

χ²(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 \ admitAdmittedRejectedTotal
Male1,1981,4932,691
Female5571,2781,835

Adjusted standardized residuals (|z| > 1.96 stands out)

gender \ admitAdmittedRejected
Male9.602−9.602
Female−9.6029.602
  • Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals.
The exact Python script · Python 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,
})

Check the assumption row first: χ2\chi^2 relies on large expected counts. Here the smallest expected count is 712, so that's safe. When expected counts are small, use the exact test the card suggests.

07

Check your understanding

Checkpoint

Check yourself

You double every count in a table. What happens to χ² and Cramér's V?

Show the answer

Answer: a

χ² scales with n, and V divides by n. That's why V measures strength and χ² doesn't.

Check yourself

A 2×3 table of 100 rows has χ² = 4. What is Cramér's V?

Show the answer

Answer: 0.2

min(r−1, c−1) = 1, so V = √(4 / (100 × 1)) = √0.04 = 0.2.

Check yourself

An odds ratio of 2 with a 95% interval from 0.9 to 4.4 is compatible with what?

Show the answer

Answer: b

The interval includes 1, so no difference is compatible with the data. And an odds ratio isn't a ratio of probabilities unless the outcome is rare.

08

Do it on your own data

In the app

Pick two categorical columns for rows and columns. The card gives χ2\chi^2, Cramér's V, and for 2×2 tables the odds ratio and Fisher's exact test.

Python
import numpy as np
from scipy import stats

table = np.array([[1198, 1493], [557, 1278]])  # admitted / rejected by gender
res = stats.chi2_contingency(table, correction=False)
n, k = table.sum(), min(table.shape) - 1
print(res.statistic, res.pvalue, np.sqrt(res.statistic / (n * k)))
print(stats.contingency.odds_ratio(table, kind="sample").statistic)
R
tab <- matrix(c(1198, 557, 1493, 1278), nrow = 2)  # admitted / rejected by gender
res <- chisq.test(tab, correct = FALSE)
v <- sqrt(res$statistic / (sum(tab) * (min(dim(tab)) - 1)))
c(res$statistic, p = res$p.value, V = v)
(tab[1, 1] * tab[2, 2]) / (tab[1, 2] * tab[2, 1])  # sample odds ratio
09

Recap

Recap
  • χ2\chi^2 tests whether there's an association, but it grows with sample size.
  • Cramér's V and phi report strength on a 0-to-1 scale.
  • In a 2×2 table, the odds ratio with its interval is usually the most useful summary.
  • Odds ratios aren't probability ratios unless the outcome is rare.

Concepts in this lesson