Joint distributions and independence
Two variables at once. Read a joint table, compute what independence would predict, and see that "uncorrelated" doesn't mean "independent".
What runs in CodeSplash
- STAT057Pearson chi square independence test Runs in CodeSplash
- χ² test of independence Verified in Python and R
You will be able to
- Read joint and marginal probabilities from a table
- Compute the counts independence predicts
- Tell independence from zero correlation, and recognize dependence over time
Read first
Two variables at once
ReadA joint distributionJoint distributionThe chance of each combination of values of two or more variables. gives the chance of each combination of values. Here are the Berkeley applicants:
| Admitted | Rejected | Total | |
|---|---|---|---|
| Men | 1,198 | 1,493 | 2,691 |
| Women | 557 | 1,278 | 1,835 |
| Total | 1,755 | 2,771 | 4,526 |
The inner cells are joint counts. The totals at the edges give each variable's marginal distributionMarginal distributionThe distribution of one variable alone, ignoring the others; the totals at a table's edges., ignoring the other one.
What independence predicts
PredictPredict first
Two variables are independentIndependenceEach observation carries its own information; no clustering, repeated measures or time dependence. when knowing one tells you nothing about the other: . If admission and gender were independent, how many men would you expect to be admitted?
Make your guess between 800 and 1300 men admitted, then reveal.
Reveal
About 1,043: . The table shows 1,198. The difference is what a χ² test measures.
Observed against expected
ExploreChange the counts. Guess the p-value first, then try the challenge: multiply a whole table by 3 and compare χ², p and Cramér's V.
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?
| A | B | C | |
|---|---|---|---|
| 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 to see the result.
Read the test
ReadFor the Berkeley table, χ² = 92.2 on 1 degree of freedom, p < .001, and Cramér's V is 0.14.
The data aren't compatible with independence overall. An earlier lesson showed that this vanishes within departments. Joint tables can hide a third variable.
χ²(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.
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
))
χ²(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.
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,
})
Uncorrelated isn't independent
ExploreCorrelation measures only straight-line association. Choose a Parabola Relationship, then compare Pearson with the other measures. Two variables can be strongly related with a correlation near zero.
CExplorable · Dependence the correlation misses
Can two variables be strongly related and still have a correlation near zero?
Pearson's r for this relationship will be about what?
Relationship
Commit your prediction above to see the result
Make your prediction to see the result.
Dependence over time
ExploreIndependence also fails from one moment to the next. In a Markov chain, tomorrow's state depends on today's. Change P(stay in A) and P(stay in B), and watch Memory per step and Long-run share.
AExplorable · A Markov chain playground
When tomorrow depends only on today, where does a process settle in the long run?
In the long run, what share of time does the chain spend in A?
The strip shows the first steps: state A in one color, B in the other. Long runs of one color mean a sticky chain.
Commit your prediction above to see the result
Make your prediction to see the result.
Tests that assume independent rows can be badly wrong for data like these.
Check your reading
CheckpointCheck yourself
A table has 100 people. A row has 40 people and a column has 30. How many people would you expect in that cell under independence?
Show the answer
Answer: 12
.
Check yourself
From the Berkeley table, what is the marginal probability of admission? Give three decimals.
Show the answer
Answer: 0.388
.
Check yourself
is symmetric around zero, and . What can you say about them?
Show the answer
Answer: b
Once you know you know exactly. Independence implies zero correlation, and the reverse doesn't hold.
Test independence in the app
In the appChoose Rows and Columns in Analyze. The card shows the expected counts behind the test, so you can see which cells drive the result.
import numpy as np
from scipy import stats
table = np.array([[1198, 1493], [557, 1278]])
chi2, p, df, expected = stats.chi2_contingency(table, correction=False)
print(chi2, df, p)
print(expected)table <- matrix(c(1198, 557, 1493, 1278), nrow = 2)
result <- chisq.test(table, correct = FALSE)
c(result$statistic, result$parameter, result$p.value)
result$expectedRecap
Recap- A joint table gives combinations. The margins give each variable alone.
- Under independence, an expected count is the row total times the column total over .
- Zero correlation doesn't imply independence, and rows over time are rarely independent.
Concepts in this lesson