Skip to content

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.

Advanced ~13 min8 steps

What runs in CodeSplash

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

01

Few causes, many items

Read

Factor 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.

02

Is the matrix worth factoring?

In the app

Before extracting anything, the card gives two checks on nine mental-ability tests.

  • Bartlett's sphericity test asks if all correlations might be zero: χ2\chi^2 = 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 0.60.6 are workable.
Exploratory factor analysisRecorded · Python and R agreeRecorded 2026-11-17 · 106 values compared
R

KMO = .75; Bartlett's χ²(36) = 904.10, p < .001

Factors
3
Variance explained
54.0%
KMO
0.7522
RMSR
0.0191

Plots

Parallel analysisHow many factors stand out above what random data would produce?
View data
EigenvalueFactorData
3.2161observed
1.6392observed
1.3653observed
0.69894observed
0.58435observed
0.49976observed
0.47317observed
0.28608observed
0.23779observed
1.3481simulated
1.2272simulated
1.1533simulated
1.0904simulated
1.0395simulated
0.97466simulated
0.92057simulated
0.86058simulated
0.80559simulated
LoadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FactorTextItemLoading
F10.20x10.1964
F20.59x10.5916
F30.03x10.0309
F10.04x20.0430
F20.51x20.5089
F3-0.12x2−0.1223
F1-0.06x3−0.0623
F20.69x30.6859
F30.02x30.0190
F10.85x40.8461
F20.02x40.0163
F30.01x40.0077
F10.89x50.8855
F2-0.06x5−0.0646
F30.01x50.0067
F10.81x60.8053
F20.08x60.0796
F3-0.01x6−0.0130
F10.04x70.0438
F2-0.15x7−0.1523
F30.74x70.7365
F1-0.03x8−0.0340
F20.13x80.1251
F30.69x80.6865
F10.03x90.0318
F20.38x90.3823
F30.46x90.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)

ItemF1F2F3h²u²
x10.19640.59160.03090.47680.5232
x20.04300.5089−0.12230.25520.7448
x3−0.06230.68590.01900.45350.5465
x40.84610.01630.00770.72790.2721
x50.8855−0.06460.00670.75370.2463
x60.80530.0796−0.01300.69140.3086
x70.0438−0.15230.73650.51860.4814
x8−0.03400.12510.68650.52020.4798
x90.03180.38230.45640.46050.5395

Variance accounted for

FactorSS loadingsProportionCumulative
F12.24024.9%24.9%
F21.34314.9%39.8%
F31.27414.2%54.0%

Factor correlations

F1F2F3
F110.32290.2133
F20.322910.2608
F30.21330.26081

Sampling adequacy by item (MSA)

ItemMSA
x10.8050
x20.7779
x30.7343
x40.7633
x50.7387
x60.8076
x70.5930
x80.6829
x90.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
))
Python

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)

ItemF1F2F3h²u²
x10.19640.59160.03090.47680.5232
x20.04300.5089−0.12230.25520.7448
x3−0.06230.68590.01900.45350.5465
x40.84610.01630.00770.72790.2721
x50.8855−0.06460.00670.75370.2463
x60.80530.0796−0.01300.69140.3086
x70.0438−0.15230.73650.51860.4814
x8−0.03400.12510.68650.52020.4798
x90.03180.38230.45640.46050.5395

Variance accounted for

FactorSS loadingsProportionCumulative
F12.24024.9%24.9%
F21.34314.9%39.8%
F31.27414.2%54.0%

Factor correlations

F1F2F3
F110.32290.2133
F20.32291.0000.2608
F30.21330.26081.000

Sampling adequacy by item (MSA)

ItemMSA
x10.8050
x20.7779
x30.7343
x40.7633
x50.7387
x60.8076
x70.5930
x80.6829
x90.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,
})
03

How many factors?

Predict

Predict 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?

Eigenvalues above 1 are enoughCompare with eigenvalues from random dataKeep adding until fit is perfect
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.

Parallel analysisHow many factors stand out above what random data would produce?
View data
factoreigenvaluekind
15.120observed
22.480observed
31.370observed
40.9200observed
50.8100observed
60.7400observed
70.6600observed
80.5800observed
90.5000observed
100.4200observed
110.2400observed
120.1600observed
11.420simulated (95th percentile)
21.300simulated (95th percentile)
31.210simulated (95th percentile)
41.130simulated (95th percentile)
51.060simulated (95th percentile)
60.9900simulated (95th percentile)
70.9300simulated (95th percentile)
80.8700simulated (95th percentile)
90.8100simulated (95th percentile)
100.7500simulated (95th percentile)
110.6900simulated (95th percentile)
120.6200simulated (95th percentile)
04

Rotation and loadings

Read

Rotation 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.

05

Name a factor

Reflect

Look 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?

06

Same analysis, two dialects

Read

statsmodels 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.

Python
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))
R
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")$loadings
07

Check your understanding

Checkpoint

Check 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.

08

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