Skip to content

CDiscover · discover.famd

Factor analysis of mixed data

What are the main dimensions of a table with both numeric and categorical variables?

Factor analysis of mixed data (FAMD): numeric variables standardized, categories weighted by their frequency, analyzed together. Eigenvalues, individual coordinates, correlations of the numeric variables and category centers. R runs FactoMineR::FAMD; Python the same decomposition.

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

A real result

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

Factor analysis of mixed dataRecorded · Python and R agreeRecorded 2026-11-17 · 62 values compared
R

FAMD of 4 numeric and 3 categorical variables: the first dimension explains 46.7% of the variance.

Plots

Scree plotHow many components carry most of the variance?
View data
DimensionCumulativeProportion of variance
10.46680.4668
20.68880.2220
30.84520.1565
40.92290.0777
50.95490.0321
60.97410.0191
70.98520.0111
80.99560.0104
910.0044
Map (dimensions 1 × 2)How do rows spread on the main components, and which variables drive each direction?

Numeric variables: correlations with the dimensions; categories: centers of their rows.

View data
KindVariableDim 1Dim 2
point−2.260−1.080
point−1.997−1.760
point−2.064−1.593
point−2.467−1.728
point−2.349−0.7809
point−2.363−1.775
point−1.452−0.8935
point−2.396−1.618
point−2.383−0.7540
point−2.047−1.079
point−2.329−1.959
point−2.229−1.591
point−1.482−0.4588
point−2.806−2.075
point−1.678−0.0644
point−2.019−1.422
point−1.607−0.8020
point−1.585−1.412
point−1.116−0.8203
point−1.164−0.9081
point−1.633−1.510
point−1.346−0.5595
point−1.472−1.210
point−2.269−1.382
point−1.284−0.5294
point−2.278−0.5636
point−2.126−0.0065
point−2.121−0.3843
point−1.8520.4363
point−1.921−0.7374
point−1.8180.6285
point−1.9510.4242
point−2.209−0.0774
point−2.731−0.3638
point−1.5430.3818
point−2.613−0.6340
point−1.4100.3919
point−2.630−0.5981
point−1.1390.8621
point−2.371−0.7342
point−1.3330.3406
point−2.1830.4532
point−2.200−0.6620
point−1.8140.8929
point−1.358−1.312
point−0.8557−0.5345
point−1.566−1.668
point−0.5948−0.2596
point−2.030−1.702
point−0.9549−0.4652
point−1.331−1.390
point−0.9185−0.4990
point−1.866−1.752
point−1.146−0.7130
point−1.672−1.764
point−0.8941−0.1111
point−1.330−1.580
point−0.6772−0.5364
point−1.863−1.684
point−0.6664−0.5224

First 60 of 345 rows.

Eigenvalues

DimensionEigenvalueProportion
14.20146.7%
21.99822.2%
31.40815.6%
40.69907.8%
50.28853.2%
60.17211.9%
70.10011.1%
80.09361.0%
90.03980.4%

Variable coordinates

Variable or categoryDim 1Dim 2Dim 3
bill_len0.66880.66060.0119
bill_dep−0.72010.37720.4858
flipper_len0.93560.05770.1160
body_mass0.90180.01890.3237
species=Adelie−1.717−0.78220.4722
species=Chinstrap−0.89372.397−0.7355
species=Gentoo2.617−0.4098−0.1590
island=Biscoe1.582−0.5655−0.0378
island=Dream−1.3351.274−0.3946
island=Torgersen−1.992−1.3721.164
sex=female−0.3897−0.5575−1.018
sex=male0.38270.54760.9995
  • 11 of 344 rows were left out because a value was missing.
Python

FAMD of 4 numeric and 3 categorical variables: the first dimension explains 46.7% of the variance.

To keep this page light, the plots are shown once, under the R tab.

Eigenvalues

DimensionEigenvalueProportion
14.20146.7%
21.99822.2%
31.40815.6%
40.69907.8%
50.28853.2%
60.17211.9%
70.10011.1%
80.09361.0%
90.03980.4%

Variable coordinates

Variable or categoryDim 1Dim 2Dim 3
bill_len0.66880.66060.0119
bill_dep−0.72010.37720.4858
flipper_len0.93560.05770.1160
body_mass0.90180.01890.3237
species=Adelie−1.717−0.78220.4722
species=Chinstrap−0.89372.397−0.7355
species=Gentoo2.617−0.4098−0.1590
island=Biscoe1.582−0.5655−0.0378
island=Dream−1.3351.274−0.3946
island=Torgersen−1.992−1.3721.164
sex=female−0.3897−0.5575−1.018
sex=male0.38270.54760.9995
  • 11 of 344 rows were left out because a value was missing.

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

  • Penguinsml_penguins · categorical: species, island, sex · numeric: bill_len, bill_dep, flipper_len, body_mass
  • Chickweight one factorml_chickweight · categorical: Diet · numeric: weight, Time
  • Pima booleanml_pima · categorical: diabetic · numeric: glu, bmi, age, ped

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

Numeric variablesnumeric · 1–300 columns
Numeric columns in the factor analysis of mixed data.
Categorical variablescategorical / boolean · 1–100 columns
Categorical columns in the factor analysis of mixed data.

Choices you make

model

Dimensions to keepdefault 5

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

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_numeric
How many independent units the analysis used; it sets precision and power.
n_categorical
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.
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 or 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 runs the FAMD decomposition directly (codesplash.ml.embed.famd, population SD as FactoMineR); R calls FactoMineR::FAMD. Rows with a missing value are left out in both. Signs are canonical over the stacked variable coordinates.
Python

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

# Factor analysis of mixed data
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.famd 1.0.0 · spec d18ac443e7be524b
# Dataset: ml_penguins (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
NUMERIC = ["bill_len", "bill_dep", "flipper_len", "body_mass"]
CATEGORICAL = ["species", "island", "sex"]
LEVELS = {
    "species": ["Adelie", "Chinstrap", "Gentoo"],
    "island": ["Biscoe", "Dream", "Torgersen"],
    "sex": ["female", "male"],
}
COLUMNS = list(dict.fromkeys(NUMERIC + CATEGORICAL))
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=COLUMNS)
n_input = len(df)
warnings = []
rows = csembed.complete_rows(df, COLUMNS)
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].reset_index(drop=True)

# %% Factor analysis of mixed data (as FactoMineR::FAMD)
n_cat = sum(len({str(v) for v in data[c]}) for c in CATEGORICAL)
rank = min(len(NUMERIC) + n_cat - len(CATEGORICAL), len(rows) - 1)
k = min(3, rank)
res = csembed.famd(data, NUMERIC, CATEGORICAL, LEVELS, k)
eig = res["eig"][:rank]
prop = eig / eig.sum()
signs = csembed.canonical_signs(res["col"])
col_coord = res["col"] * signs
row_coord = res["row"] * signs

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-72273/discover.famd/penguins/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
labels = res["labels"]
values = {
    "n": len(rows),
    "n_numeric": len(NUMERIC),
    "n_categorical": len(CATEGORICAL),
    "n_dims": len(eig),
    "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(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("Proportion of variance", prop, "numeric"),
        "cumulative": cs.col("Cumulative", np.cumsum(prop), "numeric"),
    })
]
if k >= 2:
    pick = chart_rows(len(rows))
    charts.append(cs.chart("map", "biplot", "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(labels), "categorical"),
        "label": cs.col("Variable", [""] * len(pick) + labels, "categorical"),
    }, note="Numeric variables: correlations with the dimensions; categories: centers of their rows."))
cs.publish({
    "title": "Factor analysis of mixed data",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"FAMD of {len(NUMERIC)} numeric and {len(CATEGORICAL)} categorical variables: the first dimension explains {prop[0]:.1%} of the variance.",
    "tables": [
        {"key": "variance", "title": "Eigenvalues", "columns": [
            {"key": "dim", "label": "Dimension", "type": "integer"},
            {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
            {"key": "proportion", "label": "Proportion", "type": "percent"}],
         "rows": [{"dim": j + 1, "eigenvalue": eig[j], "proportion": prop[j]} for j in range(len(eig))]},
        {"key": "coordinates", "title": "Variable coordinates", "columns": [{"key": "variable", "label": "Variable or category"}]
         + [{"key": f"d{j + 1}", "label": f"Dim {j + 1}", "type": "number"} for j in range(show)],
         "rows": [dict({"variable": lab}, **{f"d{j + 1}": col_coord[i, j] for j in range(show)}) for i, lab in enumerate(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 “Penguins” · R version 4.5.1 (2025-06-13)

# Factor analysis of mixed data
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.famd 1.0.0 · spec d18ac443e7be524b
# Dataset: ml_penguins (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
NUMERIC <- c("bill_len", "bill_dep", "flipper_len", "body_mass")
CATEGORICAL <- c("species", "island", "sex")
LEVELS <- list(
  species = c("Adelie", "Chinstrap", "Gentoo"),
  island = c("Biscoe", "Dream", "Torgersen"),
  sex = c("female", "male")
)
COLUMNS <- unique(c(NUMERIC, CATEGORICAL))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = COLUMNS))
n_input <- nrow(df)
warnings <- list()
rows <- cs_ml_complete_rows(df, COLUMNS)
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, COLUMNS, drop = FALSE]
rownames(data) <- NULL
for (f in NUMERIC) data[[f]] <- as.numeric(data[[f]])
for (f in CATEGORICAL) {
  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))
}
labels <- c(NUMERIC, unlist(lapply(CATEGORICAL, function(f) paste0(f, "=", levels(data[[f]])))))

# %% Factor analysis of mixed data (FactoMineR)
n_cat <- sum(vapply(CATEGORICAL, function(f) nlevels(data[[f]]), integer(1)))
rank <- min(length(NUMERIC) + n_cat - length(CATEGORICAL), length(rows) - 1L)
k <- min(3, rank)
m <- FactoMineR::FAMD(data, ncp = rank, graph = FALSE)  # all dimensions (eig is truncated to ncp)
eig <- unname(m$eig[seq_len(rank), 1])
prop <- eig / sum(eig)
coords <- rbind(as.matrix(m$quanti.var$coord), as.matrix(m$quali.var$coord))[, seq_len(k), drop = FALSE]
signs <- cs_ml_canonical_signs(coords)
col_coord <- sweep(unname(coords), 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-72273/discover.famd/penguins/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_numeric = length(NUMERIC), n_categorical = length(CATEGORICAL),
               n_dims = length(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("Proportion of variance", prop, "numeric"),
  cumulative = cs_col("Cumulative", cumsum(prop), "numeric")
)))
if (k >= 2) {
  pick <- chart_rows(length(rows))
  charts[[2]] <- cs_chart("map", "biplot", "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("Variable", c(rep("", length(pick)), labels), "categorical")
  ), note = "Numeric variables: correlations with the dimensions; categories: centers of their rows.")
}
cs_publish(list(
  title = "Factor analysis of mixed data",
  engine = cs_engine_info("FactoMineR", "nanoparquet"),
  n = length(rows),
  summary = sprintf("FAMD of %d numeric and %d categorical variables: the first dimension explains %.1f%% of the variance.",
                    length(NUMERIC), length(CATEGORICAL), 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 = "Proportion", type = "percent")),
         rows = lapply(seq_along(eig), function(j) list(dim = j, eigenvalue = eig[j], proportion = prop[j]))),
    list(key = "coordinates", title = "Variable coordinates",
         columns = c(list(list(key = "variable", label = "Variable or 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(variable = 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

  • Pagès J (2004). Analyse factorielle de données mixtes. Revue de Statistique Appliquée 52(4):93–111.
  • 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.famd v1.0.0.