Exploratory factor analysis
Find the few factors behind many items. Decide how many to keep with parallel analysis, choose a rotation, and read loadings without over-reading them.
What runs in CodeSplash
- Exploratory factor analysis Verified in Python and R
You will be able to
- Check that a correlation matrix is suitable for factoring
- Choose the number of factors using parallel analysis
- Interpret rotated loadings and communalities
Read first
Few causes, many items
ReadFactor analysisFactor analysisExplains correlations among many items through a few unobserved factors. supposes a few unseen factors drive the correlations among many measured items. It splits each item's variance into a part shared with the factors (its communality) and a part unique to it.
That differs from PCA, which only re-expresses all the variance. If you believe in latent traits, use factor analysis; if you want fewer columns, PCA is fine.
Is the matrix worth factoring?
In the appBefore extracting anything, the card gives two checks on nine mental-ability tests.
- Bartlett's sphericity test asks if all correlations might be zero: = 904 on 36 df, p < .001. It nearly always rejects with enough people.
- KMO asks how much of the correlation is shared: here 0.75. Values above about are workable.
KMO = .75; Bartlett's χ²(36) = 904.10, p < .001
- Factors
- 3
- Variance explained
- 54.0%
- KMO
- 0.7522
- RMSR
- 0.0191
Plots
View data
| Eigenvalue | Factor | Data |
|---|---|---|
| 3.216 | 1 | observed |
| 1.639 | 2 | observed |
| 1.365 | 3 | observed |
| 0.6989 | 4 | observed |
| 0.5843 | 5 | observed |
| 0.4997 | 6 | observed |
| 0.4731 | 7 | observed |
| 0.2860 | 8 | observed |
| 0.2377 | 9 | observed |
| 1.348 | 1 | simulated |
| 1.227 | 2 | simulated |
| 1.153 | 3 | simulated |
| 1.090 | 4 | simulated |
| 1.039 | 5 | simulated |
| 0.9746 | 6 | simulated |
| 0.9205 | 7 | simulated |
| 0.8605 | 8 | simulated |
| 0.8055 | 9 | simulated |
View data
| Factor | Text | Item | Loading |
|---|---|---|---|
| F1 | 0.20 | x1 | 0.1964 |
| F2 | 0.59 | x1 | 0.5916 |
| F3 | 0.03 | x1 | 0.0309 |
| F1 | 0.04 | x2 | 0.0430 |
| F2 | 0.51 | x2 | 0.5089 |
| F3 | -0.12 | x2 | −0.1223 |
| F1 | -0.06 | x3 | −0.0623 |
| F2 | 0.69 | x3 | 0.6859 |
| F3 | 0.02 | x3 | 0.0190 |
| F1 | 0.85 | x4 | 0.8461 |
| F2 | 0.02 | x4 | 0.0163 |
| F3 | 0.01 | x4 | 0.0077 |
| F1 | 0.89 | x5 | 0.8855 |
| F2 | -0.06 | x5 | −0.0646 |
| F3 | 0.01 | x5 | 0.0067 |
| F1 | 0.81 | x6 | 0.8053 |
| F2 | 0.08 | x6 | 0.0796 |
| F3 | -0.01 | x6 | −0.0130 |
| F1 | 0.04 | x7 | 0.0438 |
| F2 | -0.15 | x7 | −0.1523 |
| F3 | 0.74 | x7 | 0.7365 |
| F1 | -0.03 | x8 | −0.0340 |
| F2 | 0.13 | x8 | 0.1251 |
| F3 | 0.69 | x8 | 0.6865 |
| F1 | 0.03 | x9 | 0.0318 |
| F2 | 0.38 | x9 | 0.3823 |
| F3 | 0.46 | x9 | 0.4564 |
Assumptions
- Sample size — 301 cases for 9 items (33.4 per item).
- Sampling adequacy — KMO = 0.75; Bartlett χ²(36) = 904.1, p < .001.
- Communalities below 1 — Every communality is below 1.
- Convergence — Extraction converged in 137 iterations.
Pattern loadings (oblimin rotation)
| Item | F1 | F2 | F3 | h² | u² |
|---|---|---|---|---|---|
| x1 | 0.1964 | 0.5916 | 0.0309 | 0.4768 | 0.5232 |
| x2 | 0.0430 | 0.5089 | −0.1223 | 0.2552 | 0.7448 |
| x3 | −0.0623 | 0.6859 | 0.0190 | 0.4535 | 0.5465 |
| x4 | 0.8461 | 0.0163 | 0.0077 | 0.7279 | 0.2721 |
| x5 | 0.8855 | −0.0646 | 0.0067 | 0.7537 | 0.2463 |
| x6 | 0.8053 | 0.0796 | −0.0130 | 0.6914 | 0.3086 |
| x7 | 0.0438 | −0.1523 | 0.7365 | 0.5186 | 0.4814 |
| x8 | −0.0340 | 0.1251 | 0.6865 | 0.5202 | 0.4798 |
| x9 | 0.0318 | 0.3823 | 0.4564 | 0.4605 | 0.5395 |
Variance accounted for
| Factor | SS loadings | Proportion | Cumulative |
|---|---|---|---|
| F1 | 2.240 | 24.9% | 24.9% |
| F2 | 1.343 | 14.9% | 39.8% |
| F3 | 1.274 | 14.2% | 54.0% |
Factor correlations
| F1 | F2 | F3 | |
|---|---|---|---|
| F1 | 1 | 0.3229 | 0.2133 |
| F2 | 0.3229 | 1 | 0.2608 |
| F3 | 0.2133 | 0.2608 | 1 |
Sampling adequacy by item (MSA)
| Item | MSA |
|---|---|
| x1 | 0.8050 |
| x2 | 0.7779 |
| x3 | 0.7343 |
| x4 | 0.7633 |
| x5 | 0.7387 |
| x6 | 0.8076 |
| x7 | 0.5930 |
| x8 | 0.6829 |
| x9 | 0.7879 |
- Minimum-residual (iterated principal axis) extraction of the Pearson correlation matrix; oblimin rotation. Root mean square residual 0.019.
- Parallel analysis: 100 random normal datasets of 301 × 9 (seed 42); 3 eigenvalue(s) exceed the 95th percentile of the random eigenvalues.
- Likelihood-ratio fit (Bartlett-corrected): χ²(12) = 22.56, p = .032, RMSEA 0.054, TLI 0.964.
The exact R script · R R version 4.5.1 (2025-06-13)
# Exploratory factor analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.efa 2.0.1 · spec 9c15d9b0d307c56a
# Dataset: s3_hs (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# psych::fa(R, nfactors, fm = "minres" | "ml", rotate = …) fits the same model; cs_meas_efa runs the
# iterations to 1e-12 so R and Python agree exactly.
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s3_hs.parquet", col_select = c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9")]), , 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("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9")) # infinite values stop the run (registry/errors.yaml)
# %% Correlations, adequacy and parallel analysis
items <- c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9")
X <- as.matrix(df[items])
storage.mode(X) <- "double"
n <- nrow(X)
p <- ncol(X)
if (n <= p) cs_error("CS_E_TOO_FEW_ROWS", what = "Factor analysis", min = p + 1, n = n) # the correlation matrix is singular with no more cases than items
for (j in seq_len(p)) {
if (length(unique(X[, j])) < 2) cs_error("CS_E_CONSTANT", column = items[j]) # a constant item has no correlations
}
R <- stats::cor(X)
if (qr(R)$rank < p) stop("The correlation matrix is singular (an item is constant or a linear combination of others)")
km <- cs_meas_kmo(R)
bt <- cs_meas_bartlett(R, n)
eigen_r <- cs_meas_eig(R)$values
reps <- as.integer(100)
n_factors <- 3
pa_threshold <- "p95" # "p95" (95th percentile of the random eigenvalues) or "mean" (Horn 1965)
seed <- 42 # parallel analysis: the same random data in Python and R for this seed
suggested <- NULL
pa <- NULL
if (reps > 0 || is.null(n_factors)) {
pa <- cs_meas_parallel(n, p, max(reps, 20L), seed)
above <- eigen_r > pa[[pa_threshold]]
suggested <- if (all(above)) p else which(!above)[1] - 1
suggested <- max(suggested, 1)
}
k <- if (!is.null(n_factors)) as.integer(n_factors) else as.integer(suggested)
method <- "minres"
rotation <- "oblimin"
if (method == "ml" && ((p - k)^2 - (p + k)) / 2 < 0) {
stop(sprintf("%d factors are too many for %d items with maximum likelihood (negative degrees of freedom)", k, p))
}
if (k >= p) stop(sprintf("Choose fewer factors than items (%d)", p))
# %% Factor analysis
res <- cs_meas_efa(R, n, k, method, rotation)
L <- res$loadings
phi <- res$phi
fac <- paste0("F", seq_len(k))
nz <- function(v) if (is.null(v)) NA else v
values <- list(n = n, items = p, n_factors = k, suggested_factors = nz(suggested), kmo = km$overall, bartlett_chi2 = bt$chi2,
bartlett_df = bt$df, bartlett_p = bt$p, rmsr = res$rmsr, chi2 = if (res$df > 0) res$chi2 else NA, df = res$df,
chi2_p = nz(res$p), rmsea = nz(res$rmsea), tli = nz(res$tli), bic = nz(res$bic), var_explained = sum(res$prop_var))
for (i in seq_along(items)) {
for (j in seq_along(fac)) values[[sprintf("loading[%s|%s]", items[i], fac[j])]] <- L[i, j]
values[[sprintf("communality[%s]", items[i])]] <- res$communality[i]
values[[sprintf("uniqueness[%s]", items[i])]] <- res$uniqueness[i]
values[[sprintf("msa[%s]", items[i])]] <- km$per[i]
}
for (j in seq_along(fac)) {
values[[sprintf("ss[%s]", fac[j])]] <- res$ss[j]
values[[sprintf("prop_var[%s]", fac[j])]] <- res$prop_var[j]
}
if (!is.null(phi) && k > 1) {
for (a in 1:(k - 1)) for (b in (a + 1):k) values[[sprintf("phi[%s|%s]", fac[a], fac[b])]] <- phi[a, b]
}
for (i in seq_len(p)) {
values[[sprintf("eigen[%d]", i)]] <- eigen_r[i]
if (!is.null(pa)) {
values[[sprintf("pa_mean[%d]", i)]] <- pa$mean[i]
values[[sprintf("pa_p95[%d]", i)]] <- pa$p95[i]
}
}
# %% Assumptions
heywood <- items[res$communality >= 0.999]
small <- n < 100 || n < 5 * p
assumptions <- list(
list(key = "sample_size", label = "Sample size", status = if (small) "warn" else "pass",
detail = paste0(sprintf("%d cases for %d items (%.1f per item)", n, p, n / p), if (small) " — factor solutions may be unstable." else ".")),
list(key = "adequacy", label = "Sampling adequacy", status = if (km$overall < 0.6 || bt$p >= 0.05) "warn" else "pass",
detail = paste0(sprintf("KMO = %.2f", km$overall), if (km$overall < 0.6) " (below .60: the items share little common variance)" else "",
sprintf("; Bartlett χ²(%.0f) = %.1f, %s.", bt$df, bt$chi2, cs_fmt_p(bt$p)))),
list(key = "heywood", label = "Communalities below 1", status = if (length(heywood)) "fail" else "pass",
detail = if (length(heywood)) sprintf("Heywood case: %s — try fewer factors or another extraction.", paste(heywood, collapse = ", ")) else "Every communality is below 1."),
list(key = "convergence", label = "Convergence", status = if (res$converged) "pass" else "warn",
detail = if (res$converged) sprintf("Extraction converged in %d iterations.", res$iterations) else sprintf("Extraction stopped after %d iterations without converging.", res$iterations))
)
# %% Result
load_rows <- lapply(seq_along(items), function(i) {
r <- list(item = items[i])
for (j in seq_along(fac)) r[[fac[j]]] <- L[i, j]
r$h2 <- res$communality[i]
r$u2 <- res$uniqueness[i]
r
})
cumv <- cumsum(res$prop_var)
fac_rows <- lapply(seq_along(fac), function(j) list(factor = fac[j], ss = res$ss[j], prop = res$prop_var[j], cum = cumv[j]))
fcols <- lapply(fac, function(f) list(key = f, label = f, type = "number"))
tables <- list(
list(key = "loadings", title = sprintf("%s loadings (%s rotation)", if (!is.null(phi)) "Pattern" else "Factor", rotation),
columns = c(list(list(key = "item", label = "Item", type = "string")), fcols,
list(list(key = "h2", label = "h²", type = "number"), list(key = "u2", label = "u²", type = "number"))), rows = load_rows),
list(key = "factors", title = "Variance accounted for", columns = list(
list(key = "factor", label = "Factor", type = "string"), list(key = "ss", label = "SS loadings", type = "number"),
list(key = "prop", label = "Proportion", type = "percent"), list(key = "cum", label = "Cumulative", type = "percent")), rows = fac_rows)
)
if (!is.null(phi)) {
tables <- c(tables, list(list(key = "phi", title = "Factor correlations", columns = c(list(list(key = "factor", label = "", type = "string")), fcols),
rows = lapply(seq_along(fac), function(a) { r <- list(factor = fac[a]); for (b in seq_along(fac)) r[[fac[b]]] <- phi[a, b]; r }))))
}
tables <- c(tables, list(list(key = "msa", title = "Sampling adequacy by item (MSA)", columns = list(
list(key = "item", label = "Item", type = "string"), list(key = "msa", label = "MSA", type = "number")),
rows = lapply(seq_along(items), function(i) list(item = items[i], msa = km$per[i])))))
lv <- as.vector(t(L))
charts <- list(cs_chart("loadings", "matrix-heatmap", "Loadings", list(
row = cs_col("Item", rep(items, each = k), "categorical", levels = items),
col = cs_col("Factor", rep(fac, times = p), "categorical", levels = fac),
value = cs_col("Loading", lv, "numeric"),
label = cs_col("Text", sprintf("%.2f", lv), "categorical")
), controls = list(scale = "diverging")))
if (!is.null(pa)) {
charts <- c(list(cs_chart("parallel", "parallel-analysis", "Parallel analysis", list(
factor = cs_col("Factor", rep(as.double(seq_len(p)), 2), "numeric"),
eigenvalue = cs_col("Eigenvalue", c(eigen_r, pa[[pa_threshold]]), "numeric"),
kind = cs_col("Data", rep(c("observed", "simulated"), each = p), "categorical", levels = c("observed", "simulated"))
))), charts)
}
notes <- list(sprintf("%s extraction of the Pearson correlation matrix; %s rotation%s. Root mean square residual %.3f.",
if (method != "ml") "Minimum-residual (iterated principal axis)" else "Maximum-likelihood", rotation,
if (rotation %in% c("varimax", "quartimax", "promax")) " (Kaiser-normalized)" else "", res$rmsr))
if (!is.null(pa)) notes <- c(notes, sprintf("Parallel analysis: %d random normal datasets of %d × %d (seed %s); %d eigenvalue(s) exceed the %s of the random eigenvalues.",
max(reps, 20L), n, p, seed, suggested, if (pa_threshold == "p95") "95th percentile" else "mean"))
if (res$df > 0) notes <- c(notes, sprintf("Likelihood-ratio fit (Bartlett-corrected): χ²(%.0f) = %.2f, %s, RMSEA %.3f, TLI %.3f.", res$df, res$chi2, cs_fmt_p(res$p), res$rmsea, res$tli))
cs_publish(list(
method = "measurement.efa",
methodVersion = "2.0.1",
title = "Exploratory factor analysis",
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = sprintf("%d factor%s explain %.0f%% of the variance of %d items (KMO = %.2f).", k, if (k != 1) "s" else "", 100 * sum(res$prop_var), p, km$overall),
apa = sprintf("KMO = %s; Bartlett's χ²(%.0f) = %s, %s", cs_fmt_num(km$overall, 2, leading_zero = FALSE), bt$df, cs_fmt_num(bt$chi2), cs_fmt_p(bt$p)),
statistics = list(list(key = "factors", label = "Factors", value = k), list(key = "var", label = "Variance explained", value = sum(res$prop_var), format = "percent"),
list(key = "kmo", label = "KMO", value = km$overall), list(key = "rmsr", label = "RMSR", value = res$rmsr)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
KMO = .75; Bartlett's χ²(36) = 904.10, p < .001
- Factors
- 3
- Variance explained
- 54.0%
- KMO
- 0.7522
- RMSR
- 0.0191
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Sample size — 301 cases for 9 items (33.4 per item).
- Sampling adequacy — KMO = 0.75; Bartlett χ²(36) = 904.1, p < .001.
- Communalities below 1 — Every communality is below 1.
- Convergence — Extraction converged in 137 iterations.
Pattern loadings (oblimin rotation)
| Item | F1 | F2 | F3 | h² | u² |
|---|---|---|---|---|---|
| x1 | 0.1964 | 0.5916 | 0.0309 | 0.4768 | 0.5232 |
| x2 | 0.0430 | 0.5089 | −0.1223 | 0.2552 | 0.7448 |
| x3 | −0.0623 | 0.6859 | 0.0190 | 0.4535 | 0.5465 |
| x4 | 0.8461 | 0.0163 | 0.0077 | 0.7279 | 0.2721 |
| x5 | 0.8855 | −0.0646 | 0.0067 | 0.7537 | 0.2463 |
| x6 | 0.8053 | 0.0796 | −0.0130 | 0.6914 | 0.3086 |
| x7 | 0.0438 | −0.1523 | 0.7365 | 0.5186 | 0.4814 |
| x8 | −0.0340 | 0.1251 | 0.6865 | 0.5202 | 0.4798 |
| x9 | 0.0318 | 0.3823 | 0.4564 | 0.4605 | 0.5395 |
Variance accounted for
| Factor | SS loadings | Proportion | Cumulative |
|---|---|---|---|
| F1 | 2.240 | 24.9% | 24.9% |
| F2 | 1.343 | 14.9% | 39.8% |
| F3 | 1.274 | 14.2% | 54.0% |
Factor correlations
| F1 | F2 | F3 | |
|---|---|---|---|
| F1 | 1 | 0.3229 | 0.2133 |
| F2 | 0.3229 | 1.000 | 0.2608 |
| F3 | 0.2133 | 0.2608 | 1.000 |
Sampling adequacy by item (MSA)
| Item | MSA |
|---|---|
| x1 | 0.8050 |
| x2 | 0.7779 |
| x3 | 0.7343 |
| x4 | 0.7633 |
| x5 | 0.7387 |
| x6 | 0.8076 |
| x7 | 0.5930 |
| x8 | 0.6829 |
| x9 | 0.7879 |
- Minimum-residual (iterated principal axis) extraction of the Pearson correlation matrix; oblimin rotation. Root mean square residual 0.019.
- Parallel analysis: 100 random normal datasets of 301 × 9 (seed 42); 3 eigenvalue(s) exceed the 95th percentile of the random eigenvalues.
- Likelihood-ratio fit (Bartlett-corrected): χ²(12) = 22.56, p = .032, RMSEA 0.054, TLI 0.964.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Exploratory factor analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.efa 2.0.1 · spec 9c15d9b0d307c56a
# Dataset: s3_hs (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
import codesplash as cs
from codesplash.stats import measurement as ms # EFA twin of R's cs_meas_efa
# factor_analyzer.FactorAnalyzer(n_factors, method="minres"|"ml", rotation=…) and psych::fa fit the
# same models; the twin runs both engines' iterations to 1e-12 so Python and R agree exactly.
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s3_hs.parquet", columns=["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"])
n_input = len(df)
df = df.dropna(subset=["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"]) # listwise deletion over the analysis columns
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, ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"]) # infinite values stop the run (registry/errors.yaml)
# %% Correlations, adequacy and parallel analysis
items = ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"]
X = df[items].to_numpy(dtype=float)
n, p = X.shape
if n <= p: # the correlation matrix is singular with no more cases than items
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Factor analysis", min=p + 1, n=n)
for j, item in enumerate(items):
if len(np.unique(X[:, j])) < 2: # a constant item has no correlations
cs.cs_error("CS_E_CONSTANT", column=item)
R = np.corrcoef(X, rowvar=False)
if np.linalg.matrix_rank(R) < p:
raise ValueError("The correlation matrix is singular (an item is constant or a linear combination of others)")
kmo, msa = ms.kmo(R)
b_chi2, b_df, b_p = ms.bartlett(R, n)
eigen = ms.eigenvalues(R)
reps = int(100)
n_factors = 3
PA_THRESHOLD = "p95" # "p95" (95th percentile of the random eigenvalues) or "mean" (Horn 1965)
seed = 42 # parallel analysis: the same random data in Python and R for this seed
suggested = None
pa = None
if reps > 0 or n_factors is None:
pa = ms.parallel_analysis(n, p, max(reps, 20), seed)
above = eigen > pa[PA_THRESHOLD]
suggested = int(np.argmin(above)) if not above.all() else p
suggested = max(suggested, 1)
k = int(n_factors) if n_factors is not None else suggested
method = "minres"
rotation = "oblimin"
if method == "ml" and ((p - k) ** 2 - (p + k)) / 2 < 0:
raise ValueError(f"{k} factors are too many for {p} items with maximum likelihood (negative degrees of freedom)")
if k >= p:
raise ValueError(f"Choose fewer factors than items ({p})")
# %% Factor analysis
res = ms.efa(R, n, k, method, rotation)
L, phi = res["loadings"], res["phi"]
fac = [f"F{j + 1}" for j in range(k)]
values = {"n": float(n), "items": float(p), "n_factors": float(k), "suggested_factors": None if suggested is None else float(suggested),
"kmo": kmo, "bartlett_chi2": b_chi2, "bartlett_df": b_df, "bartlett_p": b_p, "rmsr": res["rmsr"],
"chi2": res["chi2"] if res["df"] > 0 else None, "df": res["df"], "chi2_p": res.get("p"), "rmsea": res.get("rmsea"),
"tli": res.get("tli"), "bic": res.get("bic"), "var_explained": float(np.sum(res["prop_var"]))}
for i, it in enumerate(items):
for j, f in enumerate(fac):
values[f"loading[{it}|{f}]"] = float(L[i, j])
values[f"communality[{it}]"] = float(res["communality"][i])
values[f"uniqueness[{it}]"] = float(res["uniqueness"][i])
values[f"msa[{it}]"] = float(msa[i])
for j, f in enumerate(fac):
values[f"ss[{f}]"] = float(res["ss"][j])
values[f"prop_var[{f}]"] = float(res["prop_var"][j])
if phi is not None:
for a in range(k):
for b in range(a + 1, k):
values[f"phi[{fac[a]}|{fac[b]}]"] = float(phi[a, b])
for i in range(p):
values[f"eigen[{i + 1}]"] = float(eigen[i])
if pa is not None:
values[f"pa_mean[{i + 1}]"] = float(pa["mean"][i])
values[f"pa_p95[{i + 1}]"] = float(pa["p95"][i])
# %% Assumptions
heywood = [it for i, it in enumerate(items) if res["communality"][i] >= 0.999]
assumptions = [
{"key": "sample_size", "label": "Sample size", "status": "warn" if n < 100 or n < 5 * p else "pass",
"detail": f"{n} cases for {p} items ({n / p:.1f} per item)" + (" — factor solutions may be unstable." if n < 100 or n < 5 * p else ".")},
{"key": "adequacy", "label": "Sampling adequacy", "status": "warn" if kmo < 0.6 or b_p >= 0.05 else "pass",
"detail": f"KMO = {kmo:.2f}" + (" (below .60: the items share little common variance)" if kmo < 0.6 else "")
+ f"; Bartlett χ²({b_df:.0f}) = {b_chi2:.1f}, {cs.fmt_p(b_p)}."},
{"key": "heywood", "label": "Communalities below 1", "status": "fail" if heywood else "pass",
"detail": f"Heywood case: {', '.join(heywood)} — try fewer factors or another extraction." if heywood else "Every communality is below 1."},
{"key": "convergence", "label": "Convergence", "status": "pass" if res["converged"] else "warn",
"detail": f"Extraction converged in {res['iterations']} iterations." if res["converged"] else f"Extraction stopped after {res['iterations']} iterations without converging."},
]
# %% Result
load_rows = [{"item": it, **{f: float(L[i, j]) for j, f in enumerate(fac)}, "h2": float(res["communality"][i]), "u2": float(res["uniqueness"][i])}
for i, it in enumerate(items)]
cum = np.cumsum(res["prop_var"])
fac_rows = [{"factor": f, "ss": float(res["ss"][j]), "prop": float(res["prop_var"][j]), "cum": float(cum[j])} for j, f in enumerate(fac)]
tables = [
{"key": "loadings", "title": f"{'Pattern' if phi is not None else 'Factor'} loadings ({rotation} rotation)", "columns": [
{"key": "item", "label": "Item", "type": "string"}, *[{"key": f, "label": f, "type": "number"} for f in fac],
{"key": "h2", "label": "h²", "type": "number"}, {"key": "u2", "label": "u²", "type": "number"}], "rows": load_rows},
{"key": "factors", "title": "Variance accounted for", "columns": [
{"key": "factor", "label": "Factor", "type": "string"}, {"key": "ss", "label": "SS loadings", "type": "number"},
{"key": "prop", "label": "Proportion", "type": "percent"}, {"key": "cum", "label": "Cumulative", "type": "percent"}], "rows": fac_rows},
]
if phi is not None:
tables.append({"key": "phi", "title": "Factor correlations", "columns": [
{"key": "factor", "label": "", "type": "string"}, *[{"key": f, "label": f, "type": "number"} for f in fac]],
"rows": [{"factor": f, **{g: float(phi[a, b]) for b, g in enumerate(fac)}} for a, f in enumerate(fac)]})
tables.append({"key": "msa", "title": "Sampling adequacy by item (MSA)", "columns": [
{"key": "item", "label": "Item", "type": "string"}, {"key": "msa", "label": "MSA", "type": "number"}],
"rows": [{"item": it, "msa": float(msa[i])} for i, it in enumerate(items)]})
charts = [cs.chart("loadings", "matrix-heatmap", "Loadings", {
"row": cs.col("Item", [it for it in items for _ in fac], "categorical", levels=items),
"col": cs.col("Factor", [f for _ in items for f in fac], "categorical", levels=fac),
"value": cs.col("Loading", [float(L[i, j]) for i in range(p) for j in range(k)], "numeric"),
"label": cs.col("Text", [f"{L[i, j]:.2f}" for i in range(p) for j in range(k)], "categorical"),
}, controls={"scale": "diverging"})]
if pa is not None:
charts.insert(0, cs.chart("parallel", "parallel-analysis", "Parallel analysis", {
"factor": cs.col("Factor", [float(i + 1) for i in range(p)] * 2, "numeric"),
"eigenvalue": cs.col("Eigenvalue", [float(v) for v in eigen] + [float(v) for v in pa[PA_THRESHOLD]], "numeric"),
"kind": cs.col("Data", ["observed"] * p + ["simulated"] * p, "categorical", levels=["observed", "simulated"]),
}))
notes = [f"{'Minimum-residual (iterated principal axis)' if method != 'ml' else 'Maximum-likelihood'} extraction of the Pearson correlation matrix; "
f"{rotation} rotation{' (Kaiser-normalized)' if rotation in ('varimax', 'quartimax', 'promax') else ''}. Root mean square residual {res['rmsr']:.3f}."]
if pa is not None:
notes.append(f"Parallel analysis: {max(reps, 20)} random normal datasets of {n} × {p} (seed {seed}); {suggested} eigenvalue(s) exceed the "
f"{'95th percentile' if PA_THRESHOLD == 'p95' else 'mean'} of the random eigenvalues.")
if res["df"] > 0:
notes.append(f"Likelihood-ratio fit (Bartlett-corrected): χ²({res['df']:.0f}) = {res['chi2']:.2f}, {cs.fmt_p(res['p'])}, RMSEA {res['rmsea']:.3f}, TLI {res['tli']:.3f}.")
cs.publish({
"method": "measurement.efa",
"methodVersion": "2.0.1",
"title": "Exploratory factor analysis",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n),
"summary": f"{k} factor{'s' if k != 1 else ''} explain {np.sum(res['prop_var']):.0%} of the variance of {p} items (KMO = {kmo:.2f}).",
"apa": f"KMO = {cs.fmt_num(kmo, 2, leading_zero=False)}; Bartlett's χ²({b_df:.0f}) = {cs.fmt_num(b_chi2)}, {cs.fmt_p(b_p)}",
"statistics": [{"key": "factors", "label": "Factors", "value": float(k)}, {"key": "var", "label": "Variance explained", "value": float(np.sum(res["prop_var"])), "format": "percent"},
{"key": "kmo", "label": "KMO", "value": kmo}, {"key": "rmsr", "label": "RMSR", "value": res["rmsr"]}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
How many factors?
PredictPredict first
You must choose how many factors to keep. Eigenvalues measure how much each one explains, but even pure noise produces some eigenvalues above 1.
Which approach accounts for that?
Reveal
Compare with random data. Parallel analysisParallel analysisKeeps factors whose eigenvalues exceed those from random data of the same size. simulates data of the same size with no factors, and keeps factors whose eigenvalues beat the noise (beat 95% of the random datasets). Here it suggests 3 factors. Kaiser's rule (eigenvalue above 1) tends to keep too many.
View data
| factor | eigenvalue | kind |
|---|---|---|
| 1 | 5.120 | observed |
| 2 | 2.480 | observed |
| 3 | 1.370 | observed |
| 4 | 0.9200 | observed |
| 5 | 0.8100 | observed |
| 6 | 0.7400 | observed |
| 7 | 0.6600 | observed |
| 8 | 0.5800 | observed |
| 9 | 0.5000 | observed |
| 10 | 0.4200 | observed |
| 11 | 0.2400 | observed |
| 12 | 0.1600 | observed |
| 1 | 1.420 | simulated (95th percentile) |
| 2 | 1.300 | simulated (95th percentile) |
| 3 | 1.210 | simulated (95th percentile) |
| 4 | 1.130 | simulated (95th percentile) |
| 5 | 1.060 | simulated (95th percentile) |
| 6 | 0.9900 | simulated (95th percentile) |
| 7 | 0.9300 | simulated (95th percentile) |
| 8 | 0.8700 | simulated (95th percentile) |
| 9 | 0.8100 | simulated (95th percentile) |
| 10 | 0.7500 | simulated (95th percentile) |
| 11 | 0.6900 | simulated (95th percentile) |
| 12 | 0.6200 | simulated (95th percentile) |
Rotation and loadings
ReadRotation changes how the same solution is expressed so that each item leans on few factors.
- Oblimin or promax let factors correlate, which is the usual reality for human traits.
- Varimax or quartimax force them to be uncorrelated.
A loadingFactor loadingHow strongly an item relates to a factor. Standardized loadings near 1 mean the item mostly reflects that factor. is an item's relation to a factor. Look for clear patterns, not single large numbers. Name a factor only after reading its items.
Together, the factors here explain 54.0% of the items' variance.
Name a factor
ReflectLook back at the loadings on the card. Which tests load on each factor, and what name would you give it? Could a colleague give the same tests a different name?
Same analysis, two dialects
Readstatsmodels uses principal-axis factoring here and psych uses minres, so small differences are normal, and factors can come out in another order or with flipped signs. CodeSplash's two engines match at the tier shown on the card.
import pandas as pd
from statsmodels.multivariate.factor import Factor
df = pd.read_csv("s3_hs.csv")
items = df[[f"x{i}" for i in range(1, 10)]]
fa = Factor(items, n_factor=3, method="pa").fit()
fa.rotate("oblimin")
print(pd.DataFrame(fa.loadings, index=items.columns).round(2))library(psych)
df <- read.csv("s3_hs.csv")
items <- df[, paste0("x", 1:9)]
fa.parallel(items, fa = "fa")
fa(items, nfactors = 3, rotate = "oblimin", fm = "minres")$loadingsCheck your understanding
CheckpointCheck yourself
Why is parallel analysis preferred to "keep eigenvalues above 1"?
Show the answer
Answer: a
Parallel analysis uses what noise alone would produce as its yardstick.
Check yourself
You're measuring anxiety and depression and expect the two to be related. Which rotation fits?
Show the answer
Answer: b
An orthogonal rotation forces a zero correlation you don't believe. Rotation doesn't change model fit, only how it's expressed.
Check yourself
You used EFA on 300 people to choose a three-factor structure. Now you want to show that structure holds. What should you do?
Show the answer
Answer: b
Data that suggested a structure can't confirm it. Use a new sample, or split yours before you start.
Recap
Recap- Factor analysis models shared variance through a few latent factors.
- Use parallel analysis to choose how many.
- Use oblique rotation unless you have good reason not to.
- Exploration suggests a structure; confirmation needs new data.
Concepts in this lesson