GMeasurement · measurement.efa
Exploratory factor analysis
Which few underlying factors explain how a set of items or measures correlate?
Exploratory factor analysis of the items' correlation matrix: minimum-residual (principal axis) or maximum-likelihood extraction, varimax / quartimax / oblimin / promax rotation, loadings, communalities, factor correlations, sampling adequacy (KMO, Bartlett) and parallel analysis to choose the number of factors (by default a factor must beat the 95th percentile of random-data eigenvalues; Horn's mean rule is an option).
A real result
Example “Hs three oblimin”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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.
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.
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
- Hs three oblimins3_hs · items: x1, x2, x3, x4, x5, x6, x7, x8, x9
- Hs ml promaxs3_hs · items: x1, x2, x3, x4, x5, x6, x7, x8, x9
- Twofactor parallel varimaxs3_twofactor · items: anx_1, anx_2, anx_3, anx 4, mood_1, mood_2, mood_3, mood_4
- Twofactor parallel means3_twofactor · items: anx_1, anx_2, anx_3, anx 4, mood_1, mood_2, mood_3, mood_4
- Claims weak structureml_claims · items: claims, severity, amount, exposure, age, power
- Claims weak structure meanml_claims · items: claims, severity, amount, exposure, age, power
- Attitude one factorattitude · items: rating, complaints, privileges, learning, raises, critical, advance
- Degenerate constants3_hs · items: x1, x2, x3, x4, x5, x6, x7, x8, x9
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Model selection and structure (penalized, stepwise, SEM) · Statistics Guide · D — Predict an outcome
- Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Itemsnumeric · 3–200 columns
- The items or measures to factor (rows with a missing value are left out). Likert items are analyzed as numbers (Pearson correlations).
Choices you make
model
- Number of factorsdefault —
Leave empty to use the number parallel analysis suggests.
- Extractiondefault minres
Maximum likelihood adds a χ² test of fit; minimum residual makes no distributional assumption.
- Minimum residual (principal axis)(default) — Minimizes residual correlations and doesn't need normal data; the usual choice.
- Maximum likelihood — Assumes multivariate normal data and gives fit tests; pick it when you want them.
- Rotationdefault oblimin
Rotation makes factors easier to interpret. Oblique rotations let factors correlate; orthogonal ones keep them apart.
- Oblimin (oblique: factors may correlate)(default) — Lets factors correlate; the usual choice for psychological scales, which tend to overlap.
- Promax (oblique) — Lets factors correlate, starting from varimax; fast on large item sets.
- Varimax (orthogonal) — Keeps factors uncorrelated and makes each load on few variables; easy to read.
- Quartimax (orthogonal) — Keeps factors uncorrelated and makes each variable load on few factors; tends to give one general factor.
- None (unrotated) — Shows the raw extraction; hard to read, but useful for seeing a general factor.
statistics
- Parallel analysis samplesdefault 100
Random normal datasets of the same size (the same draws in Python and R for a seed); 0 skips parallel analysis when the number of factors is given.
- Parallel analysis cutoffdefault p95
The eigenvalue an observed factor must beat to count. The 95th percentile guards against keeping noise factors.
- 95th percentile of the random eigenvalues(default) — Keeps a factor only when its eigenvalue beats 95% of the random datasets (Glorfeld 1995); the recommended rule.
- Mean of the random eigenvalues (Horn 1965) — Horn's original rule; it tends to keep one factor too many, especially in large samples. This was the only rule before version 2.0.0.
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.
Sample size
Factor solutions need enough cases — often 100 or more and several per item.
Sampling adequacy
KMO ≥ .60 and a significant Bartlett test indicate the correlations are worth factoring.
Communalities below 1
A communality at or above 1 (a Heywood case) means the solution is improper — try fewer factors.
Convergence
Extraction iterations reached the tolerance.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- items
- How many items (questions or variables) entered the analysis.
- n_factors
- How many independent units the analysis used; it sets precision and power.
- suggested_factors
- Keeps factors whose eigenvalues exceed those from random data of the same size.
- kmo
- How suited a correlation matrix is to factor analysis. Near 1 is good; below 0.5 suggests factors won't hold.
- bartlett_chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- bartlett_df
- How much independent information is left to estimate variability after fitting the model.
- bartlett_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- rmsr
- Summaries of how well a factor or structural model reproduces the data's covariances, such as CFI, TLI, RMSEA and SRMR.
- chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- df
- How much independent information is left to estimate variability after fitting the model.
- chi2_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- rmsea
- Summaries of how well a factor or structural model reproduces the data's covariances, such as CFI, TLI, RMSEA and SRMR.
- tli
- Summaries of how well a factor or structural model reproduces the data's covariances, such as CFI, TLI, RMSEA and SRMR.
- bic
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- var_explained
- The share of total variation captured by a component or set of components.
Per group, level or term: loading[<item>|<factor>], communality[<item>], uniqueness[<item>], msa[<item>], ss[<factor>], prop_var[<factor>], phi[<factor>|<factor>], eigen[<k>], pa_mean[<k>], pa_p95[<k>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines run the same deterministic algorithms (codesplash.stats.measurement.efa ↔ cs_meas_efa): iterated principal axis / EM to 1e-12 and gradient-projection rotation to a gradient norm of 1e-7, so they agree to about 1e-12. psych::fa reaches the same minres/ML solution (unrotated loadings agree to 1e-5) but stops its rotations earlier (stats::varimax and GPArotation use eps = 1e-5), so rotated loadings differ from psych by up to about 5e-4.
- Parallel analysis uses principal-component eigenvalues of random normal data drawn from the shared Wichmann–Hill stream (Horn 1965); psych::fa.parallel draws its own random numbers and also reports factor eigenvalues.
The exact script CodeSplash ran for example “Hs three oblimin” · 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,
})
The exact script CodeSplash ran for example “Hs three oblimin” · 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
))
Sources
- Fabrigar, L. R., Wegener, D. T., MacCallum, R. C., & Strahan, E. J. (1999). Evaluating the use of exploratory factor analysis in psychological research. Psychological Methods, 4, 272–299.
- Bernaards, C. A., & Jennrich, R. I. (2005). Gradient projection algorithms and software for arbitrary rotation criteria in factor analysis. Educational and Psychological Measurement, 65, 676–696.
- Horn, J. L. (1965). A rationale and test for the number of factors in factor analysis. Psychometrika, 30, 179–185.
- Glorfeld, L. W. (1995). An improvement on Horn's parallel analysis methodology for selecting the correct number of factors to retain. Educational and Psychological Measurement, 55, 377–393.
- Revelle, W. (2025). psych: Procedures for psychological, psychometric, and personality research. R package.
From the CodeSplash method registry · measurement.efa v2.0.1.