Skip to content

CDiscover · discover.mca

Multiple correspondence analysis

How do the categories of several categorical variables go together?

Multiple correspondence analysis (MCA) of categorical variables: eigenvalues, category and individual coordinates, a scree plot and a category map. R runs FactoMineR::MCA; Python runs the same correspondence analysis of the indicator matrix, so both give identical coordinates.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Titanic”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Multiple correspondence analysisRecorded · Python and R agreeRecorded 2026-11-09 · 51 values compared
R

MCA of 4 variables: the first dimension explains 29.7% of the inertia.

Eigenvalues

DimensionEigenvalueShare of inertia
10.445129.7%
20.305020.3%
30.250016.7%
40.205013.7%
50.178511.9%
60.11637.8%

Category coordinates

CategoryDim 1Dim 2Dim 3
Class=1st1.152−1.231−0.8900
Class=2nd0.65130.25252.392
Class=3rd0.13061.070−0.6591
Class=Crew−0.7369−0.48270.0823
Sex=Male−0.4276−0.00240.0025
Sex=Female1.5750.0089−0.0093
Age=Child1.3022.9430.0238
Age=Adult−0.0678−0.1533−0.0012
Survived=No−0.50950.1902−0.0038
Survived=Yes1.068−0.39870.0079
Python

MCA of 4 variables: the first dimension explains 29.7% of the inertia.

Eigenvalues

DimensionEigenvalueShare of inertia
10.445129.7%
20.305020.3%
30.250016.7%
40.205013.7%
50.178511.9%
60.11637.8%

Category coordinates

CategoryDim 1Dim 2Dim 3
Class=1st1.152−1.231−0.8900
Class=2nd0.65130.25252.392
Class=3rd0.13061.070−0.6591
Class=Crew−0.7369−0.48270.0823
Sex=Male−0.4276−0.00240.0025
Sex=Female1.5750.0089−0.0093
Age=Child1.3022.9430.0238
Age=Adult−0.0678−0.1533−0.0012
Survived=No−0.50950.1902−0.0038
Survived=Yes1.068−0.39870.0079

Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.

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

  • Titanicml_titanic · features: Class, Sex, Age, Survived
  • Penguins missing categoryml_penguins · features: species, island, sex
  • Penguins listwiseml_penguins · features: species, island, sex

In the guides

Where it sits in the decision guides

  • Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Categorical variablescategorical / boolean · 2–100 columns
Categorical columns whose categories are mapped together.

Choices you make

model

Dimensions to keepdefault 5

Number of dimensions to keep for the map and the export.

preprocess

Missing valuesdefault listwise

Leave out rows with a missing value, or treat missing as its own category.

  • Leave out rows with a missing value(default) — Leaves out rows with any missing value; the clean choice when few are missing.
  • Treat missing as its own category — Treats missing as a category of its own; pick it when being missing may carry meaning.

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_variables
How many independent units the analysis used; it sets precision and power.
n_categories
How many independent units the analysis used; it sets precision and power.
n_dims
How many independent units the analysis used; it sets precision and power.
inertia
A PCA-like map for categorical columns, which places categories and rows that occur together close to each other.
cum2
The share of total variation captured by a component or set of components.

Per group, level or term: eigen[<k>], prop[<k>], coord[<k>:<variable>=<level>], row_check[<k>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses numpy, pandas; R uses FactoMineR.

Default traps between the two languages

  • Python computes the correspondence analysis of the indicator matrix directly (codesplash.ml.embed.mca); R calls FactoMineR::MCA. Eigenvalues are uncorrected (no Benzécri adjustment) in both; signs are canonical (largest |category coordinate| positive).
Python

The exact script CodeSplash ran for example “Titanic” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Multiple correspondence analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mca 1.0.0 · spec 93e96b2019049eb0
# Dataset: ml_titanic (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed

def chart_rows(n, cap=2000):
    return np.arange(n) if n <= cap else np.unique(np.linspace(0, n - 1, cap).round().astype(int))

# %% Data
FEATURES = ["Class", "Sex", "Age", "Survived"]
LEVELS = {
    "Class": ["1st", "2nd", "3rd", "Crew"],
    "Sex": ["Male", "Female"],
    "Age": ["Child", "Adult"],
    "Survived": ["No", "Yes"],
}
df = pd.read_parquet("tests/parity/fixtures/ml_titanic.parquet", columns=FEATURES)
n_input = len(df)
warnings = []
rows = csembed.complete_rows(df, FEATURES)
if len(rows) < n_input:
    warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
data = df.iloc[rows].astype("object")

# %% Multiple correspondence analysis (= CA of the indicator matrix, as FactoMineR::MCA)
n_dims_all = sum(len({str(v) for v in data[c]}) for c in FEATURES) - len(FEATURES)
k = min(3, n_dims_all, len(rows) - 1)
res = csembed.mca(data, FEATURES, LEVELS, k)
eig = res["eig"][: min(n_dims_all, len(rows) - 1)]
prop = eig / eig.sum()
signs = csembed.canonical_signs(res["col"])  # largest |category coordinate| positive
col_coord = res["col"] * signs
row_coord = res["row"] * signs

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-57623/discover.mca/titanic/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(k):
    emb[f"dim_{j + 1}"] = row_coord[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)

# %% Result
values = {
    "n": len(rows),
    "n_variables": len(FEATURES),
    "n_categories": len(res["labels"]),
    "n_dims": len(eig),
    "inertia": float(eig.sum()),
    "cum2": float(prop[:2].sum()) if len(eig) >= 2 else float("nan"),
}
for j in range(len(eig)):
    values[f"eigen[{j + 1}]"] = float(eig[j])
    values[f"prop[{j + 1}]"] = float(prop[j])
for j in range(k):
    values[f"row_check[{j + 1}]"] = csembed.checksum(row_coord[:, j], rows)
    for i, lab in enumerate(res["labels"]):
        values[f"coord[{j + 1}:{lab}]"] = float(col_coord[i, j])
show = min(k, 3)
charts = [
    cs.chart("scree", "scree-plot", "Scree plot", {
        "component": cs.col("Dimension", list(range(1, len(eig) + 1)), "numeric"),
        "variance": cs.col("Share of inertia", prop, "numeric"),
        "cumulative": cs.col("Cumulative", np.cumsum(prop), "numeric"),
    })
]
if k >= 2:
    pick = chart_rows(len(rows))
    charts.append(cs.chart("map", "biplot", "Category map (dimensions 1 × 2)", {
        "x": cs.col("Dim 1", np.concatenate([row_coord[pick, 0], col_coord[:, 0]]), "numeric"),
        "y": cs.col("Dim 2", np.concatenate([row_coord[pick, 1], col_coord[:, 1]]), "numeric"),
        "kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * len(res["labels"]), "categorical"),
        "label": cs.col("Category", [""] * len(pick) + res["labels"], "categorical"),
    }))
cs.publish({
    "title": "Multiple correspondence analysis",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"MCA of {len(FEATURES)} variables: the first dimension explains {prop[0]:.1%} of the inertia.",
    "tables": [
        {"key": "variance", "title": "Eigenvalues", "columns": [
            {"key": "dim", "label": "Dimension", "type": "integer"},
            {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
            {"key": "proportion", "label": "Share of inertia", "type": "percent"}],
         "rows": [{"dim": j + 1, "eigenvalue": eig[j], "proportion": prop[j]} for j in range(len(eig))]},
        {"key": "categories", "title": "Category coordinates", "columns": [{"key": "category", "label": "Category"}]
         + [{"key": f"d{j + 1}", "label": f"Dim {j + 1}", "type": "number"} for j in range(show)],
         "rows": [dict({"category": lab}, **{f"d{j + 1}": col_coord[i, j] for j in range(show)}) for i, lab in enumerate(res["labels"])]},
    ],
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})
R

The exact script CodeSplash ran for example “Titanic” · R version 4.5.1 (2025-06-13)

# Multiple correspondence analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mca 1.0.0 · spec 93e96b2019049eb0
# Dataset: ml_titanic (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(FactoMineR))

chart_rows <- function(n, cap = 2000) if (n <= cap) seq_len(n) else unique(round(seq(1, n, length.out = cap)))

# %% Data
FEATURES <- c("Class", "Sex", "Age", "Survived")
LEVELS <- list(
  Class = c("1st", "2nd", "3rd", "Crew"),
  Sex = c("Male", "Female"),
  Age = c("Child", "Adult"),
  Survived = c("No", "Yes")
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_titanic.parquet", col_select = FEATURES))
n_input <- nrow(df)
warnings <- list()
rows <- cs_ml_complete_rows(df, FEATURES)
if (length(rows) < n_input) {
  warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
}
data <- df[rows + 1L, FEATURES, drop = FALSE]
for (f in FEATURES) {
  lv <- if (is.null(LEVELS[[f]])) sort(unique(as.character(data[[f]])), method = "radix") else LEVELS[[f]]
  data[[f]] <- droplevels(factor(as.character(data[[f]]), levels = lv))  # stored order, unused levels dropped
}
labels <- unlist(lapply(FEATURES, function(f) paste0(f, "=", levels(data[[f]]))))

# %% Multiple correspondence analysis (FactoMineR)
n_dims_all <- length(labels) - length(FEATURES)
k <- min(3, n_dims_all, length(rows) - 1L)
m <- FactoMineR::MCA(data, ncp = min(n_dims_all, length(rows) - 1L), graph = FALSE)  # all dimensions (eig is truncated to ncp)
eig <- unname(m$eig[, 1])
prop <- eig / sum(eig)
signs <- cs_ml_canonical_signs(m$var$coord[, seq_len(k), drop = FALSE])  # largest |category coordinate| positive
col_coord <- sweep(unname(as.matrix(m$var$coord[, seq_len(k), drop = FALSE])), 2, signs, "*")
row_coord <- sweep(unname(as.matrix(m$ind$coord[, seq_len(k), drop = FALSE])), 2, signs, "*")

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-57623/discover.mca/titanic/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(k)) emb[[paste0("dim_", j)]] <- row_coord[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))

# %% Result
values <- list(n = length(rows), n_variables = length(FEATURES), n_categories = length(labels),
               n_dims = length(eig), inertia = sum(eig), cum2 = if (length(eig) >= 2) sum(prop[1:2]) else NaN)
for (j in seq_along(eig)) {
  values[[sprintf("eigen[%d]", j)]] <- eig[j]
  values[[sprintf("prop[%d]", j)]] <- prop[j]
}
for (j in seq_len(k)) {
  values[[sprintf("row_check[%d]", j)]] <- cs_ml_checksum(row_coord[, j], rows)
  for (i in seq_along(labels)) values[[sprintf("coord[%d:%s]", j, labels[i])]] <- col_coord[i, j]
}
show <- min(k, 3L)
charts <- list(cs_chart("scree", "scree-plot", "Scree plot", list(
  component = cs_col("Dimension", seq_along(eig), "numeric"),
  variance = cs_col("Share of inertia", prop, "numeric"),
  cumulative = cs_col("Cumulative", cumsum(prop), "numeric")
)))
if (k >= 2) {
  pick <- chart_rows(length(rows))
  charts[[2]] <- cs_chart("map", "biplot", "Category map (dimensions 1 × 2)", list(
    x = cs_col("Dim 1", c(row_coord[pick, 1], col_coord[, 1]), "numeric"),
    y = cs_col("Dim 2", c(row_coord[pick, 2], col_coord[, 2]), "numeric"),
    kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", length(labels))), "categorical"),
    label = cs_col("Category", c(rep("", length(pick)), labels), "categorical")
  ))
}
cs_publish(list(
  title = "Multiple correspondence analysis",
  engine = cs_engine_info("FactoMineR", "nanoparquet"),
  n = length(rows),
  summary = sprintf("MCA of %d variables: the first dimension explains %.1f%% of the inertia.", length(FEATURES), 100 * prop[1]),
  tables = list(
    list(key = "variance", title = "Eigenvalues",
         columns = list(list(key = "dim", label = "Dimension", type = "integer"),
                        list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
                        list(key = "proportion", label = "Share of inertia", type = "percent")),
         rows = lapply(seq_along(eig), function(j) list(dim = j, eigenvalue = eig[j], proportion = prop[j]))),
    list(key = "categories", title = "Category coordinates",
         columns = c(list(list(key = "category", label = "Category")),
                     lapply(seq_len(show), function(j) list(key = paste0("d", j), label = paste("Dim", j), type = "number"))),
         rows = lapply(seq_along(labels), function(i) {
           r <- list(category = labels[i])
           for (j in seq_len(show)) r[[paste0("d", j)]] <- col_coord[i, j]
           r
         }))
  ),
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))

Sources

  • Husson F, Lê S, Pagès J (2017). Exploratory Multivariate Analysis by Example Using R, 2nd ed. CRC Press.
  • Lê S, Josse J, Husson F (2008). FactoMineR: an R package for multivariate analysis. J Stat Softw 25(1).

From the CodeSplash method registry · discover.mca v1.0.0.