CAssociation · contingency.ca
Correspondence analysis (CA)
How do the categories of two variables relate — which rows and columns of the table go together?
Correspondence analysis turns a two-way table of counts into a map. Rows with similar profiles sit close together, as do columns with similar profiles, and the dimensions summarize the departures from independence that the χ² test measures (the total inertia is χ²/n). It reports the share of inertia per dimension, each level's mass, coordinates, contributions and cos² (quality), and the χ² test. Use a count column when each row of the data is one cell of the table.
A real result
Example “Smoke counts”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Correspondence analysis, total inertia = 0.085, χ²(12) = 16.44, p = .172
- Total inertia
- 0.0852
- χ²
- 16.442
- p
- .172
- Shown by 2 dimensions
- 99.5%
Plots
View data
| Level | Mass | Set | Dimension 1 (87.8%) | Dimension 2 (11.8%) |
|---|---|---|---|---|
| Senior managers | 0.0570 | staff | 0.0658 | 0.1937 |
| Junior managers | 0.0933 | staff | −0.2590 | 0.2433 |
| Senior employees | 0.2642 | staff | 0.3806 | 0.0107 |
| Junior employees | 0.4560 | staff | −0.2330 | −0.0577 |
| Secretaries | 0.1295 | staff | 0.2011 | −0.0789 |
| Non-smoker | 0.3161 | smoking | 0.3933 | 0.0305 |
| Light | 0.2332 | smoking | −0.0995 | −0.1411 |
| Medium | 0.3212 | smoking | −0.1963 | −0.0074 |
| Heavy | 0.1295 | smoking | −0.2938 | 0.1978 |
View data
| Dimension | Cumulative share | Share of inertia |
|---|---|---|
| 1 | 0.8776 | 0.8776 |
| 2 | 0.9951 | 0.1176 |
| 3 | 1 | 0.0049 |
Assumptions
- Expected counts (for the χ² p-value) — 35% of cells expect fewer than 5 (smallest 1.4). The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.
- Counts of independent units — CA describes the table; the χ² test treats every count as an independent unit.
Principal inertias
| Dimension | Principal inertia | Share | Cumulative |
|---|---|---|---|
| 1 | 0.0748 | 87.8% | 87.8% |
| 2 | 0.0100 | 11.8% | 99.5% |
| 3 | 0.0004 | 0.5% | 100.0% |
Rows (staff)
| staff | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Senior managers | 0.0570 | 3.1% | 0.8926 | 0.0658 | 0.3% | 0.0922 | 0.1937 | 21.4% | 0.8003 |
| Junior managers | 0.0933 | 13.9% | 0.9911 | −0.2590 | 8.4% | 0.5264 | 0.2433 | 55.1% | 0.4647 |
| Senior employees | 0.2642 | 45.0% | 0.9998 | 0.3806 | 51.2% | 0.9990 | 0.0107 | 0.3% | 0.0008 |
| Junior employees | 0.4560 | 30.8% | 0.9998 | −0.2330 | 33.1% | 0.9419 | −0.0577 | 15.2% | 0.0579 |
| Secretaries | 0.1295 | 7.1% | 0.9986 | 0.2011 | 7.0% | 0.8653 | −0.0789 | 8.1% | 0.1333 |
Columns (smoking)
| smoking | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Non-smoker | 0.3161 | 57.7% | 1.0000 | 0.3933 | 65.4% | 0.9940 | 0.0305 | 2.9% | 0.0060 |
| Light | 0.2332 | 8.3% | 0.9840 | −0.0995 | 3.1% | 0.3267 | −0.1411 | 46.3% | 0.6573 |
| Medium | 0.3212 | 14.8% | 0.9832 | −0.1963 | 16.6% | 0.9818 | −0.0074 | 0.2% | 0.0014 |
| Heavy | 0.1295 | 19.2% | 0.9946 | −0.2938 | 15.0% | 0.6844 | 0.1978 | 50.6% | 0.3102 |
- Principal coordinates in the tables; the map shows both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across). Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension.
Correspondence analysis, total inertia = 0.085, χ²(12) = 16.44, p = .172
- Total inertia
- 0.0852
- χ²
- 16.442
- p
- .172
- Shown by 2 dimensions
- 99.5%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Expected counts (for the χ² p-value) — 35% of cells expect fewer than 5 (smallest 1.4). The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.
- Counts of independent units — CA describes the table; the χ² test treats every count as an independent unit.
Principal inertias
| Dimension | Principal inertia | Share | Cumulative |
|---|---|---|---|
| 1 | 0.0748 | 87.8% | 87.8% |
| 2 | 0.0100 | 11.8% | 99.5% |
| 3 | 0.0004 | 0.5% | 100.0% |
Rows (staff)
| staff | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Senior managers | 0.0570 | 3.1% | 0.8926 | 0.0658 | 0.3% | 0.0922 | 0.1937 | 21.4% | 0.8003 |
| Junior managers | 0.0933 | 13.9% | 0.9911 | −0.2590 | 8.4% | 0.5264 | 0.2433 | 55.1% | 0.4647 |
| Senior employees | 0.2642 | 45.0% | 0.9998 | 0.3806 | 51.2% | 0.9990 | 0.0107 | 0.3% | 0.0008 |
| Junior employees | 0.4560 | 30.8% | 0.9998 | −0.2330 | 33.1% | 0.9419 | −0.0577 | 15.2% | 0.0579 |
| Secretaries | 0.1295 | 7.1% | 0.9986 | 0.2011 | 7.0% | 0.8653 | −0.0789 | 8.1% | 0.1333 |
Columns (smoking)
| smoking | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Non-smoker | 0.3161 | 57.7% | 1.0000 | 0.3933 | 65.4% | 0.9940 | 0.0305 | 2.9% | 0.0060 |
| Light | 0.2332 | 8.3% | 0.9840 | −0.0995 | 3.1% | 0.3267 | −0.1411 | 46.3% | 0.6573 |
| Medium | 0.3212 | 14.8% | 0.9832 | −0.1963 | 16.6% | 0.9818 | −0.0074 | 0.2% | 0.0014 |
| Heavy | 0.1295 | 19.2% | 0.9946 | −0.2938 | 15.0% | 0.6844 | 0.1978 | 50.6% | 0.3102 |
- Principal coordinates in the tables; the map shows both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across). Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension.
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
- Smoke countsrep2_smoke · cols: smoking · count: count · rows: staff
- Hair eyehair_eye · cols: eye · rows: hair
- Housing column principalhousing · cols: Sat · rows: Type
- Housing one dimensionhousing · cols: Cont · rows: Type
- Degenerate single levelhair_eye · cols: eye · rows: hair
- Degenerate constanthair_eye · cols: eye · rows: hair
In the guides
Where it sits in the decision guides
- Categorical–categorical: χ², Fisher, Cramér's V · Statistics Guide · C — Test association
- Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Rowscategorical / boolean · 1 column · 2–50 levels
- The variable whose levels form the table's rows.
- Columnscategorical / boolean · 1 column · 2–50 levels
- The variable whose levels form the table's columns.
- Count (frequency weight)numeric · 0–1 column
- For tabulated data: the count of each row's cell (leave empty when every row is one unit).
Choices you make
model
- Dimensionsdefault 2
Dimensions shown in the tables (all dimensions are in the inertia table).
- Mapdefault symmetric
Which coordinates the map draws.
- Symmetric(default) — Both sets in principal coordinates: read distances within rows and within columns, not between a row and a column.
- Rows principal — Rows in principal, columns in standard coordinates: a biplot where a row sits toward the columns it has more of.
- Columns principal — Columns in principal, rows in standard coordinates.
hypothesis
- Significance leveldefault 0.05
Level used for the χ² test.
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 (for the χ² p-value)
The χ² p-value is approximate when more than 20% of cells expect fewer than 5; the map itself does not depend on it.
Counts of independent unitsNot checked from data: state why it holds
The χ² test treats every count as an independent unit; CA as a description does not need it.
What it reports
- Tests: Rows and columns are independent
- n
- Pearson χ² for independence of the table (n × total inertia), with df = (rows − 1)(columns − 1).
- n_rows
- Maps the rows and columns of a two-way table so similar profiles sit close; its dimensions split the χ² association.
- n_cols
- Maps the rows and columns of a two-way table so similar profiles sit close; its dimensions split the χ² association.
- dims
- Maps the rows and columns of a two-way table so similar profiles sit close; its dimensions split the χ² association.
- total_inertia
- Total inertia is χ²/n, the table's departure from independence; each dimension's principal inertia is its share of it.
- chisq
- Pearson χ² for independence of the table (n × total inertia), with df = (rows − 1)(columns − 1).
- df
- Pearson χ² for independence of the table (n × total inertia), with df = (rows − 1)(columns − 1).
- p
- Pearson χ² for independence of the table (n × total inertia), with df = (rows − 1)(columns − 1).
- cum2
- Total inertia is χ²/n, the table's departure from independence; each dimension's principal inertia is its share of it.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
Per group, level or term: eigen[<k>], share[<k>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines run the codesplash twins (SVD of the standardized residuals, the same sign rule), so every number matches. FactoMineR::CA gives the same inertias and coordinates up to the sign of each dimension (checked in tests/crosscheck/w5_rep2.R), and Greenacre's smoking table reproduces the published principal inertias 0.0748, 0.0100 and 0.0004.
The exact script CodeSplash ran for example “Smoke counts” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Correspondence analysis (CA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.ca 1.0.0 · spec 2da30e50a0d783b6
# Dataset: rep2_smoke (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash.stats import multiview as mvw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/rep2_smoke.parquet", columns=["staff", "smoking", "count"])
n_input = len(df)
df["staff"] = pd.Categorical(df["staff"], categories=["Senior managers", "Junior managers", "Senior employees", "Junior employees", "Secretaries"]) # stored level order
df["smoking"] = pd.Categorical(df["smoking"], categories=["Non-smoker", "Light", "Medium", "Heavy"]) # stored level order
df = df.dropna(subset=["staff", "smoking", "count"]) # listwise deletion over the analysis columns
df["staff"] = df["staff"].cat.remove_unused_categories()
df["smoking"] = df["smoking"].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, ["staff", "smoking", "count"]) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Correspondence analysis (Benzécri 1973; Greenacre 2017): the χ² distances between the row profiles and
# between the column profiles of a two-way table, shown on a few dimensions from the SVD of the
# standardized residuals.
row_var = "staff"
col_var = "smoking"
count_var = "count"
K_REQ = int(2)
MAP = "symmetric" # symmetric | row_principal | column_principal
alpha = 0.05
w = df[count_var].to_numpy(dtype=float) if count_var else np.ones(len(df))
if count_var and np.any(w < 0):
cs.cs_error("CS_E_INVALID_VALUES", column=count_var, requirement="non-negative counts", count=int(np.sum(w < 0)))
row_levels = [str(x) for x in df[row_var].cat.categories]
col_levels = [str(x) for x in df[col_var].cat.categories]
N = np.zeros((len(row_levels), len(col_levels)))
np.add.at(N, (df[row_var].cat.codes.to_numpy(), df[col_var].cat.codes.to_numpy()), w)
keep_r = N.sum(axis=1) > 0
keep_c = N.sum(axis=0) > 0
notes = []
if not keep_r.all() or not keep_c.all():
gone = [row_levels[i] for i in np.flatnonzero(~keep_r)] + [col_levels[j] for j in np.flatnonzero(~keep_c)]
notes.append(f"Levels with a total count of zero were left out: {', '.join(gone)}.")
N = N[keep_r][:, keep_c]
row_levels = [lv for lv, k_ in zip(row_levels, keep_r) if k_]
col_levels = [lv for lv, k_ in zip(col_levels, keep_c) if k_]
check_groups(row_levels, row_var, minimum=2)
check_groups(col_levels, col_var, minimum=2)
fit = mvw.ca(N)
dims = fit["dims"]
K = min(K_REQ, dims)
total = fit["total"]
share = fit["eigen"] / total if total > 0 else np.full(dims, np.nan)
df_chi = (len(row_levels) - 1) * (len(col_levels) - 1)
p_chi = float(stats.chi2.sf(fit["chisq"], df_chi))
expected = np.outer(N.sum(axis=1), N.sum(axis=0)) / fit["n"]
# %% Assumptions
small = float(np.mean(expected < 5))
assumptions = [
{"key": "expected", "label": "Expected counts (for the χ² p-value)", "status": "ok" if small <= 0.2 and expected.min() >= 1 else "warn",
"detail": f"{small:.0%} of cells expect fewer than 5 (smallest {expected.min():.2g}). " + ("The χ² p-value is reliable." if small <= 0.2 and expected.min() >= 1
else "The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.")},
{"key": "profiles", "label": "Counts of independent units", "status": "info",
"detail": "CA describes the table; the χ² test treats every count as an independent unit."},
]
# %% Result
values = {"n": fit["n"], "n_rows": len(row_levels), "n_cols": len(col_levels), "dims": dims,
"total_inertia": total, "chisq": fit["chisq"], "df": df_chi, "p": p_chi,
"cum2": float(np.sum(share[:2])) if total > 0 else float("nan")}
for j in range(dims):
values[f"eigen[{j + 1}]"] = float(fit["eigen"][j])
values[f"share[{j + 1}]"] = float(share[j])
values["missing_share"] = n_dropped / n_input if n_input else 0.0
cum = np.cumsum(share)
tables = [{"key": "inertia", "title": "Principal inertias",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Principal inertia", "type": "number"},
{"key": "share", "label": "Share", "type": "percent"}, {"key": "cumulative", "label": "Cumulative", "type": "percent"}],
"rows": [{"dimension": j + 1, "eigen": float(fit["eigen"][j]), "share": float(share[j]), "cumulative": float(cum[j])} for j in range(dims)]}]
def side_table(key, title, var, levels, mass, inertia, coord, ctr, cos2):
cols = [{"key": "level", "label": var, "type": "string"}, {"key": "mass", "label": "Mass", "type": "number"},
{"key": "inertia", "label": "Share of inertia", "type": "percent"}, {"key": "quality", "label": f"Quality ({K} dim.)", "type": "number"}]
for j in range(K):
cols += [{"key": f"coord{j + 1}", "label": f"Dim. {j + 1}", "type": "number"},
{"key": f"ctr{j + 1}", "label": f"Contribution {j + 1}", "type": "percent"},
{"key": f"cos{j + 1}", "label": f"cos² {j + 1}", "type": "number"}]
rows = []
for i, lv in enumerate(levels):
row = {"level": lv, "mass": float(mass[i]), "inertia": float(inertia[i] / total) if total > 0 else float("nan"),
"quality": float(np.nansum(cos2[i, :K])) if not np.all(np.isnan(cos2[i, :K])) else float("nan")}
for j in range(K):
row.update({f"coord{j + 1}": float(coord[i, j]), f"ctr{j + 1}": float(ctr[i, j]), f"cos{j + 1}": float(cos2[i, j])})
rows.append(row)
return {"key": key, "title": title, "columns": cols, "rows": rows}
tables.append(side_table("rows", f"Rows ({row_var})", row_var, row_levels, fit["row_mass"], fit["row_inertia"], fit["row_coord"], fit["row_ctr"], fit["row_cos2"]))
tables.append(side_table("cols", f"Columns ({col_var})", col_var, col_levels, fit["col_mass"], fit["col_inertia"], fit["col_coord"], fit["col_ctr"], fit["col_cos2"]))
charts = [cs.chart("scree", "scree-plot", "Principal inertias", {
"component": cs.col("Dimension", np.arange(1, dims + 1, dtype=float)),
"variance": cs.col("Share of inertia", share),
"cumulative": cs.col("Cumulative share", cum)})]
if dims >= 2 and K >= 2:
rc = fit["row_coord"] if MAP in ("symmetric", "row_principal") else fit["row_std"]
cc = fit["col_coord"] if MAP in ("symmetric", "column_principal") else fit["col_std"]
charts.insert(0, cs.chart("map", "ca-map", "Correspondence analysis map", {
"x": cs.col(f"Dimension 1 ({share[0]:.1%})", np.concatenate([rc[:, 0], cc[:, 0]])),
"y": cs.col(f"Dimension 2 ({share[1]:.1%})", np.concatenate([rc[:, 1], cc[:, 1]])),
"set": cs.col("Set", [row_var] * len(row_levels) + [col_var] * len(col_levels), "categorical"),
"label": cs.col("Level", row_levels + col_levels, "categorical"),
"mass": cs.col("Mass", np.concatenate([fit["row_mass"], fit["col_mass"]]))},
controls={"map": MAP}))
summary = (f"Correspondence analysis of {row_var} ({len(row_levels)} levels) by {col_var} ({len(col_levels)} levels), total count {fit['n']:g}: "
f"total inertia {total:.4f} (χ² = {fit['chisq']:.2f}, df = {df_chi}, {cs.fmt_p(p_chi)}). "
+ (f"The first two dimensions show {share[0]:.1%} and {share[1]:.1%} of it ({share[0] + share[1]:.1%} together)." if dims >= 2
else f"The one dimension shows all of it."))
cs.publish({
"method": "contingency.ca",
"methodVersion": "1.0.0",
"title": "Correspondence analysis",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(round(fit["n"])) if float(fit["n"]).is_integer() else fit["n"],
"summary": summary,
"apa": f"Correspondence analysis, total inertia = {total:.3f}, χ²({df_chi}) = {fit['chisq']:.2f}, {cs.fmt_p(p_chi)}",
"statistics": [{"key": "total_inertia", "label": "Total inertia", "value": total},
{"key": "chisq", "label": "χ²", "value": fit["chisq"]}, {"key": "p", "label": "p", "value": p_chi, "format": "p"},
{"key": "cum2", "label": "Shown by 2 dimensions", "value": values["cum2"], "format": "percent"}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes + [f"Principal coordinates in the tables; the map shows {'both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across)' if MAP == 'symmetric' else ('rows in principal and columns in standard coordinates (row-principal biplot)' if MAP == 'row_principal' else 'columns in principal and rows in standard coordinates (column-principal biplot)')}. "
"Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension."],
"values": values,
"charts": charts,
})
The exact script CodeSplash ran for example “Smoke counts” · R version 4.5.1 (2025-06-13)
# Correspondence analysis (CA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.ca 1.0.0 · spec 2da30e50a0d783b6
# Dataset: rep2_smoke (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep2_smoke.parquet", col_select = c("staff", "smoking", "count")))
n_input <- nrow(df)
df[["staff"]] <- factor(df[["staff"]], levels = c("Senior managers", "Junior managers", "Senior employees", "Junior employees", "Secretaries")) # stored level order
df[["smoking"]] <- factor(df[["smoking"]], levels = c("Non-smoker", "Light", "Medium", "Heavy")) # stored level order
df <- df[stats::complete.cases(df[c("staff", "smoking", "count")]), , 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("staff", "smoking", "count")) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Correspondence analysis (Benzécri 1973; Greenacre 2017): the χ² distances between the row profiles and
# between the column profiles of a two-way table, shown on a few dimensions from the SVD of the
# standardized residuals.
row_var <- "staff"
col_var <- "smoking"
count_var <- "count"
K_REQ <- as.integer(2)
MAP <- "symmetric" # symmetric | row_principal | column_principal
alpha <- 0.05
w <- if (!is.null(count_var)) as.double(df[[count_var]]) else rep(1, nrow(df))
if (!is.null(count_var) && any(w < 0)) cs_error("CS_E_INVALID_VALUES", column = count_var, requirement = "non-negative counts", count = sum(w < 0))
row_levels <- levels(df[[row_var]])
col_levels <- levels(df[[col_var]])
N <- matrix(0, length(row_levels), length(col_levels))
ri <- as.integer(df[[row_var]])
ci <- as.integer(df[[col_var]])
for (t in seq_along(w)) N[ri[t], ci[t]] <- N[ri[t], ci[t]] + w[t]
keep_r <- rowSums(N) > 0
keep_c <- colSums(N) > 0
notes <- character(0)
if (!all(keep_r) || !all(keep_c)) {
notes <- c(notes, sprintf("Levels with a total count of zero were left out: %s.", paste(c(row_levels[!keep_r], col_levels[!keep_c]), collapse = ", ")))
}
N <- N[keep_r, keep_c, drop = FALSE]
row_levels <- row_levels[keep_r]
col_levels <- col_levels[keep_c]
cs_check_groups(row_levels, row_var, minimum = 2)
cs_check_groups(col_levels, col_var, minimum = 2)
fit <- cs_mview_ca(N)
dims <- fit$dims
K <- min(K_REQ, dims)
total <- fit$total
share <- if (total > 0) fit$eigen / total else rep(NaN, dims)
df_chi <- (length(row_levels) - 1) * (length(col_levels) - 1)
p_chi <- stats::pchisq(fit$chisq, df_chi, lower.tail = FALSE)
expected <- outer(rowSums(N), colSums(N)) / fit$n
# %% Assumptions
small <- mean(expected < 5)
ok_exp <- small <= 0.2 && min(expected) >= 1
assumptions <- list(
list(key = "expected", label = "Expected counts (for the χ² p-value)", status = if (ok_exp) "ok" else "warn",
detail = paste0(sprintf("%.0f%% of cells expect fewer than 5 (smallest %s). ", 100 * small, format(signif(min(expected), 2))),
if (ok_exp) "The χ² p-value is reliable."
else "The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.")),
list(key = "profiles", label = "Counts of independent units", status = "info",
detail = "CA describes the table; the χ² test treats every count as an independent unit.")
)
# %% Result
values <- list(n = fit$n, n_rows = length(row_levels), n_cols = length(col_levels), dims = dims,
total_inertia = total, chisq = fit$chisq, df = df_chi, p = p_chi,
cum2 = if (total > 0) sum(share[seq_len(min(2, dims))]) else NaN)
for (j in seq_len(dims)) {
values[[sprintf("eigen[%d]", j)]] <- fit$eigen[j]
values[[sprintf("share[%d]", j)]] <- share[j]
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
cum <- cumsum(share)
tables <- list(list(key = "inertia", title = "Principal inertias",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "eigen", label = "Principal inertia", type = "number"),
list(key = "share", label = "Share", type = "percent"), list(key = "cumulative", label = "Cumulative", type = "percent")),
rows = lapply(seq_len(dims), function(j) list(dimension = j, eigen = fit$eigen[j], share = share[j], cumulative = cum[j]))))
side_table <- function(key, title, var, levs, mass, inertia, coord, ctr, cos2) {
cols <- list(list(key = "level", label = var, type = "string"), list(key = "mass", label = "Mass", type = "number"),
list(key = "inertia", label = "Share of inertia", type = "percent"), list(key = "quality", label = sprintf("Quality (%d dim.)", K), type = "number"))
for (j in seq_len(K)) {
cols <- c(cols, list(list(key = sprintf("coord%d", j), label = sprintf("Dim. %d", j), type = "number"),
list(key = sprintf("ctr%d", j), label = sprintf("Contribution %d", j), type = "percent"),
list(key = sprintf("cos%d", j), label = sprintf("cos² %d", j), type = "number")))
}
rows <- lapply(seq_along(levs), function(i) {
cq <- cos2[i, seq_len(K)]
row <- list(level = levs[i], mass = mass[i], inertia = if (total > 0) inertia[i] / total else NaN,
quality = if (all(is.nan(cq))) NaN else sum(cq, na.rm = TRUE))
for (j in seq_len(K)) {
row[[sprintf("coord%d", j)]] <- coord[i, j]
row[[sprintf("ctr%d", j)]] <- ctr[i, j]
row[[sprintf("cos%d", j)]] <- cos2[i, j]
}
row
})
list(key = key, title = title, columns = cols, rows = rows)
}
tables[[2]] <- side_table("rows", sprintf("Rows (%s)", row_var), row_var, row_levels, fit$row_mass, fit$row_inertia, fit$row_coord, fit$row_ctr, fit$row_cos2)
tables[[3]] <- side_table("cols", sprintf("Columns (%s)", col_var), col_var, col_levels, fit$col_mass, fit$col_inertia, fit$col_coord, fit$col_ctr, fit$col_cos2)
charts <- list(cs_chart("scree", "scree-plot", "Principal inertias", list(
component = cs_col("Dimension", as.double(seq_len(dims))),
variance = cs_col("Share of inertia", share),
cumulative = cs_col("Cumulative share", cum))))
if (dims >= 2 && K >= 2) {
rc <- if (MAP %in% c("symmetric", "row_principal")) fit$row_coord else fit$row_std
cc <- if (MAP %in% c("symmetric", "column_principal")) fit$col_coord else fit$col_std
charts <- c(list(cs_chart("map", "ca-map", "Correspondence analysis map", list(
x = cs_col(sprintf("Dimension 1 (%.1f%%)", 100 * share[1]), c(rc[, 1], cc[, 1])),
y = cs_col(sprintf("Dimension 2 (%.1f%%)", 100 * share[2]), c(rc[, 2], cc[, 2])),
set = cs_col("Set", c(rep(row_var, length(row_levels)), rep(col_var, length(col_levels))), "categorical"),
label = cs_col("Level", c(row_levels, col_levels), "categorical"),
mass = cs_col("Mass", c(fit$row_mass, fit$col_mass))), controls = list(map = MAP))), charts)
}
summary <- paste0(sprintf("Correspondence analysis of %s (%d levels) by %s (%d levels), total count %s: total inertia %.4f (χ² = %.2f, df = %d, %s). ",
row_var, length(row_levels), col_var, length(col_levels), format(fit$n), total, fit$chisq, as.integer(df_chi), cs_fmt_p(p_chi)),
if (dims >= 2) sprintf("The first two dimensions show %.1f%% and %.1f%% of it (%.1f%% together).", 100 * share[1], 100 * share[2], 100 * (share[1] + share[2]))
else "The one dimension shows all of it.")
map_note <- switch(MAP,
symmetric = "both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across)",
row_principal = "rows in principal and columns in standard coordinates (row-principal biplot)",
"columns in principal and rows in standard coordinates (column-principal biplot)")
cs_publish(list(
method = "contingency.ca",
methodVersion = "1.0.0",
title = "Correspondence analysis",
engine = cs_engine_info("stats", "nanoparquet"),
n = fit$n,
summary = summary,
apa = sprintf("Correspondence analysis, total inertia = %.3f, χ²(%d) = %.2f, %s", total, as.integer(df_chi), fit$chisq, cs_fmt_p(p_chi)),
statistics = list(list(key = "total_inertia", label = "Total inertia", value = total),
list(key = "chisq", label = "χ²", value = fit$chisq), list(key = "p", label = "p", value = p_chi, format = "p"),
list(key = "cum2", label = "Shown by 2 dimensions", value = values$cum2, format = "percent")),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = as.list(c(notes, paste0("Principal coordinates in the tables; the map shows ", map_note, ". ",
"Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension."))),
values = values,
charts = charts
))
Sources
- Benzécri, J.-P. (1973). L'Analyse des Données, Vol. 2: L'Analyse des Correspondances. Dunod.
- Greenacre, M. (1984). Theory and Applications of Correspondence Analysis. Academic Press.
- Greenacre, M. (2017). Correspondence Analysis in Practice (3rd ed.). Chapman & Hall/CRC.
From the CodeSplash method registry · contingency.ca v1.0.0.