GMeasurement · measurement.cfa
Confirmatory factor analysis and structural equation models
Does a hypothesized measurement or path model fit the covariances of the observed variables, and how strong are its loadings and paths?
Maximum-likelihood confirmatory factor analysis and structural equation models written in lavaan's model syntax (=~ measures, ~ regressions, ~~ variances and covariances, fixed values and equality labels). Reports estimates with standard errors and standardized values, R², and fit: χ² test, CFI, TLI, RMSEA with its 90% interval, SRMR, AIC and BIC. Local fit shows where a model misfits: modification indices with the expected change of each parameter not in the model, and residual correlations. Each factor gets McDonald's ω and its average variance extracted.
A real result
Example “Hs three factor”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
χ²(24, N = 301) = 85.31, p < .001, CFI = .93, RMSEA = .092, SRMR = .065
- χ²
- 85.306
- df
- 24
- CFI
- 0.9306
- RMSEA
- 0.0921
- SRMR
- 0.0652
Plots
View data
| Factor | Text | Indicator | Loading |
|---|---|---|---|
| visual | 0.77 | x1 | 0.7719 |
| textual | x1 | 0 | |
| speed | x1 | 0 | |
| visual | 0.42 | x2 | 0.4236 |
| textual | x2 | 0 | |
| speed | x2 | 0 | |
| visual | 0.58 | x3 | 0.5811 |
| textual | x3 | 0 | |
| speed | x3 | 0 | |
| visual | x4 | 0 | |
| textual | 0.85 | x4 | 0.8516 |
| speed | x4 | 0 | |
| visual | x5 | 0 | |
| textual | 0.86 | x5 | 0.8551 |
| speed | x5 | 0 | |
| visual | x6 | 0 | |
| textual | 0.84 | x6 | 0.8380 |
| speed | x6 | 0 | |
| visual | x7 | 0 | |
| textual | x7 | 0 | |
| speed | 0.57 | x7 | 0.5695 |
| visual | x8 | 0 | |
| textual | x8 | 0 | |
| speed | 0.72 | x8 | 0.7230 |
| visual | x9 | 0 | |
| textual | x9 | 0 | |
| speed | 0.67 | x9 | 0.6650 |
View data
| With | Text | Variable | Residual correlation |
|---|---|---|---|
| x1 | x1 | 0 | |
| x2 | -0.03 | x1 | −0.0296 |
| x3 | -0.01 | x1 | −0.0079 |
| x4 | 0.07 | x1 | 0.0713 |
| x5 | -0.01 | x1 | −0.0092 |
| x6 | 0.06 | x1 | 0.0602 |
| x7 | -0.14 | x1 | −0.1400 |
| x8 | -0.04 | x1 | −0.0387 |
| x9 | 0.15 | x1 | 0.1488 |
| x1 | -0.03 | x2 | −0.0296 |
| x2 | x2 | 0 | |
| x3 | 0.09 | x2 | 0.0937 |
| x4 | -0.01 | x2 | −0.0125 |
| x5 | -0.03 | x2 | −0.0267 |
| x6 | 0.03 | x2 | 0.0298 |
| x7 | -0.19 | x2 | −0.1892 |
| x8 | -0.05 | x2 | −0.0518 |
| x9 | 0.07 | x2 | 0.0735 |
| x1 | -0.01 | x3 | −0.0079 |
| x2 | 0.09 | x3 | 0.0937 |
| x3 | x3 | 0 | |
| x4 | -0.07 | x3 | −0.0683 |
| x5 | -0.15 | x3 | −0.1506 |
| x6 | -0.03 | x3 | −0.0256 |
| x7 | -0.08 | x3 | −0.0838 |
| x8 | -0.01 | x3 | −0.0117 |
| x9 | 0.15 | x3 | 0.1468 |
| x1 | 0.07 | x4 | 0.0713 |
| x2 | -0.01 | x4 | −0.0125 |
| x3 | -0.07 | x4 | −0.0683 |
| x4 | x4 | 0 | |
| x5 | 0.01 | x4 | 0.0050 |
| x6 | -0.01 | x4 | −0.0092 |
| x7 | 0.04 | x4 | 0.0366 |
| x8 | -0.07 | x4 | −0.0673 |
| x9 | 0.05 | x4 | 0.0476 |
| x1 | -0.01 | x5 | −0.0092 |
| x2 | -0.03 | x5 | −0.0267 |
| x3 | -0.15 | x5 | −0.1506 |
| x4 | 0.01 | x5 | 0.0050 |
| x5 | x5 | 0 | |
| x6 | 0.00 | x5 | 0.0034 |
| x7 | -0.04 | x5 | −0.0358 |
| x8 | -0.04 | x5 | −0.0363 |
| x9 | 0.07 | x5 | 0.0666 |
| x1 | 0.06 | x6 | 0.0602 |
| x2 | 0.03 | x6 | 0.0298 |
| x3 | -0.03 | x6 | −0.0256 |
| x4 | -0.01 | x6 | −0.0092 |
| x5 | 0.00 | x6 | 0.0034 |
| x6 | x6 | 0 | |
| x7 | -0.01 | x6 | −0.0140 |
| x8 | -0.02 | x6 | −0.0219 |
| x9 | 0.06 | x6 | 0.0565 |
| x1 | -0.14 | x7 | −0.1400 |
| x2 | -0.19 | x7 | −0.1892 |
| x3 | -0.08 | x7 | −0.0838 |
| x4 | 0.04 | x7 | 0.0366 |
| x5 | -0.04 | x7 | −0.0358 |
| x6 | -0.01 | x7 | −0.0140 |
First 60 of 81 rows.
Assumptions
- Sample size — 301 cases for 21 free parameters.
- Identification — 24 degrees of freedom (45 variances and covariances, 21 free parameters).
- Proper solution — Every variance is positive and every standardized value lies within ±1.
- Model fit — CFI 0.931, TLI 0.896, RMSEA 0.092, SRMR 0.065.
- Local fit — MI above 10 with a standardized change above 0.2: visual measured by x9 (MI 36.4, +0.52); x7 with x8 (MI 34.1, +0.86); visual measured by x7 (MI 18.6, -0.35); x8 with x9 (MI 14.9, -0.81). Largest residual correlation: x2 with x7 (r = -0.189).
- Convergence — lavaan's optimizer converged.
Parameter estimates
| Label | Estimate | SE | z | p | 95% CI low | 95% CI high | Standardized | |||
|---|---|---|---|---|---|---|---|---|---|---|
| visual | measured by | x1 | — | 1 | — | — | — | — | — | 0.7719 |
| visual | measured by | x2 | — | 0.5535 | 0.0997 | 5.554 | < .001 | 0.3582 | 0.7488 | 0.4236 |
| visual | measured by | x3 | — | 0.7294 | 0.1091 | 6.685 | < .001 | 0.5155 | 0.9432 | 0.5811 |
| textual | measured by | x4 | — | 1 | — | — | — | — | — | 0.8516 |
| textual | measured by | x5 | — | 1.113 | 0.0654 | 17.014 | < .001 | 0.9849 | 1.241 | 0.8551 |
| textual | measured by | x6 | — | 0.9261 | 0.0554 | 16.703 | < .001 | 0.8175 | 1.035 | 0.8380 |
| speed | measured by | x7 | — | 1 | — | — | — | — | — | 0.5695 |
| speed | measured by | x8 | — | 1.180 | 0.1650 | 7.152 | < .001 | 0.8566 | 1.503 | 0.7230 |
| speed | measured by | x9 | — | 1.082 | 0.1512 | 7.155 | < .001 | 0.7852 | 1.378 | 0.6650 |
| x1 | with | x1 | — | 0.5491 | 0.1136 | 4.833 | < .001 | 0.3264 | 0.7717 | 0.4042 |
| x2 | with | x2 | — | 1.134 | 0.1017 | 11.146 | < .001 | 0.9345 | 1.333 | 0.8206 |
| x3 | with | x3 | — | 0.8443 | 0.0906 | 9.317 | < .001 | 0.6667 | 1.022 | 0.6623 |
| x4 | with | x4 | — | 0.3712 | 0.0477 | 7.779 | < .001 | 0.2776 | 0.4647 | 0.2748 |
| x5 | with | x5 | — | 0.4463 | 0.0584 | 7.642 | < .001 | 0.3318 | 0.5607 | 0.2689 |
| x6 | with | x6 | — | 0.3562 | 0.0430 | 8.277 | < .001 | 0.2719 | 0.4405 | 0.2977 |
| x7 | with | x7 | — | 0.7994 | 0.0814 | 9.823 | < .001 | 0.6399 | 0.9589 | 0.6757 |
| x8 | with | x8 | — | 0.4877 | 0.0742 | 6.573 | < .001 | 0.3423 | 0.6331 | 0.4772 |
| x9 | with | x9 | — | 0.5661 | 0.0707 | 8.003 | < .001 | 0.4275 | 0.7048 | 0.5578 |
| visual | with | visual | — | 0.8093 | 0.1455 | 5.564 | < .001 | 0.5242 | 1.094 | 1 |
| textual | with | textual | — | 0.9795 | 0.1121 | 8.737 | < .001 | 0.7598 | 1.199 | 1 |
| speed | with | speed | — | 0.3837 | 0.0862 | 4.451 | < .001 | 0.2148 | 0.5527 | 1 |
| visual | with | textual | — | 0.4082 | 0.0735 | 5.552 | < .001 | 0.2641 | 0.5523 | 0.4585 |
| visual | with | speed | — | 0.2622 | 0.0563 | 4.660 | < .001 | 0.1519 | 0.3725 | 0.4705 |
| textual | with | speed | — | 0.1735 | 0.0493 | 3.518 | < .001 | 0.0768 | 0.2701 | 0.2830 |
Model fit
| Measure | Value |
|---|---|
| χ² | 85.306 |
| df | 24 |
| p | 8.503e-9 |
| CFI | 0.9306 |
| TLI | 0.8958 |
| RMSEA | 0.0921 |
| RMSEA 90% CI low | 0.0714 |
| RMSEA 90% CI high | 0.1137 |
| SRMR | 0.0652 |
| Log-likelihood | −3737.74 |
| AIC | 7517.49 |
| BIC | 7595.34 |
Variance explained (R²)
| Variable | R² |
|---|---|
| x1 | 0.5958 |
| x2 | 0.1794 |
| x3 | 0.3377 |
| x4 | 0.7252 |
| x5 | 0.7311 |
| x6 | 0.7023 |
| x7 | 0.3243 |
| x8 | 0.5228 |
| x9 | 0.4422 |
Modification indices (largest, MI > 3.84)
| MI | Expected change | Standardized change | |||
|---|---|---|---|---|---|
| visual | measured by | x9 | 36.411 | 0.5770 | 0.5152 |
| x7 | with | x8 | 34.145 | 0.5364 | 0.8592 |
| visual | measured by | x7 | 18.631 | −0.4219 | −0.3489 |
| x8 | with | x9 | 14.946 | −0.4231 | −0.8052 |
| textual | measured by | x3 | 9.151 | −0.2716 | −0.2381 |
| x2 | with | x7 | 8.918 | −0.1827 | −0.1919 |
| textual | measured by | x1 | 8.903 | 0.3503 | 0.2975 |
| x2 | with | x3 | 8.532 | 0.2182 | 0.2231 |
| x3 | with | x5 | 7.858 | −0.1301 | −0.2119 |
| visual | measured by | x5 | 7.441 | −0.2099 | −0.1466 |
| x1 | with | x9 | 7.335 | 0.1379 | 0.2473 |
| x4 | with | x6 | 6.220 | −0.2348 | −0.6458 |
| x4 | with | x7 | 5.920 | 0.0982 | 0.1802 |
| x1 | with | x7 | 5.420 | −0.1291 | −0.1949 |
| x7 | with | x9 | 5.183 | −0.1867 | −0.2775 |
| textual | measured by | x9 | 4.796 | 0.1384 | 0.1360 |
| visual | measured by | x8 | 4.295 | −0.2104 | −0.1872 |
| x3 | with | x9 | 4.126 | 0.1017 | 0.1470 |
Reliability and convergent validity
| Factor | Indicators | ω | AVE |
|---|---|---|---|
| visual | 3 | 0.6253 | 0.3710 |
| textual | 3 | 0.8852 | 0.7195 |
| speed | 3 | 0.6878 | 0.4298 |
- lavaan::sem(fixed.x = FALSE): maximum likelihood (normal likelihood, covariances with divisor N), expected-information standard errors; first loadings fixed to 1, all variances free, exogenous variables and pure outcomes covary.
χ²(24, N = 301) = 85.31, p < .001, CFI = .93, RMSEA = .092, SRMR = .065
- χ²
- 85.306
- df
- 24
- CFI
- 0.9306
- RMSEA
- 0.0921
- SRMR
- 0.0652
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Sample size — 301 cases for 21 free parameters.
- Identification — 24 degrees of freedom (45 variances and covariances, 21 free parameters).
- Proper solution — Every variance is positive and every standardized value lies within ±1.
- Model fit — CFI 0.931, TLI 0.896, RMSEA 0.092, SRMR 0.065.
- Local fit — MI above 10 with a standardized change above 0.2: visual measured by x9 (MI 36.4, +0.52); x7 with x8 (MI 34.1, +0.86); visual measured by x7 (MI 18.6, -0.35); x8 with x9 (MI 14.9, -0.81). Largest residual correlation: x2 with x7 (r = -0.189).
- Convergence — Converged in 74 iterations.
Parameter estimates
| Label | Estimate | SE | z | p | 95% CI low | 95% CI high | Standardized | |||
|---|---|---|---|---|---|---|---|---|---|---|
| visual | measured by | x1 | 1 | — | — | — | — | — | 0.7719 | |
| visual | measured by | x2 | 0.5535 | 0.0997 | 5.554 | < .001 | 0.3582 | 0.7488 | 0.4236 | |
| visual | measured by | x3 | 0.7294 | 0.1091 | 6.685 | < .001 | 0.5155 | 0.9432 | 0.5811 | |
| textual | measured by | x4 | 1 | — | — | — | — | — | 0.8516 | |
| textual | measured by | x5 | 1.113 | 0.0654 | 17.014 | < .001 | 0.9849 | 1.241 | 0.8551 | |
| textual | measured by | x6 | 0.9261 | 0.0554 | 16.703 | < .001 | 0.8175 | 1.035 | 0.8380 | |
| speed | measured by | x7 | 1 | — | — | — | — | — | 0.5695 | |
| speed | measured by | x8 | 1.180 | 0.1650 | 7.152 | < .001 | 0.8566 | 1.503 | 0.7230 | |
| speed | measured by | x9 | 1.082 | 0.1512 | 7.155 | < .001 | 0.7852 | 1.378 | 0.6650 | |
| x1 | with | x1 | 0.5491 | 0.1136 | 4.833 | < .001 | 0.3264 | 0.7717 | 0.4042 | |
| x2 | with | x2 | 1.134 | 0.1017 | 11.146 | < .001 | 0.9345 | 1.333 | 0.8206 | |
| x3 | with | x3 | 0.8443 | 0.0906 | 9.317 | < .001 | 0.6667 | 1.022 | 0.6623 | |
| x4 | with | x4 | 0.3712 | 0.0477 | 7.779 | < .001 | 0.2776 | 0.4647 | 0.2748 | |
| x5 | with | x5 | 0.4463 | 0.0584 | 7.642 | < .001 | 0.3318 | 0.5607 | 0.2689 | |
| x6 | with | x6 | 0.3562 | 0.0430 | 8.277 | < .001 | 0.2719 | 0.4405 | 0.2977 | |
| x7 | with | x7 | 0.7994 | 0.0814 | 9.823 | < .001 | 0.6399 | 0.9589 | 0.6757 | |
| x8 | with | x8 | 0.4877 | 0.0742 | 6.573 | < .001 | 0.3423 | 0.6331 | 0.4772 | |
| x9 | with | x9 | 0.5661 | 0.0707 | 8.003 | < .001 | 0.4275 | 0.7048 | 0.5578 | |
| visual | with | visual | 0.8093 | 0.1455 | 5.564 | < .001 | 0.5242 | 1.094 | 1 | |
| textual | with | textual | 0.9795 | 0.1121 | 8.737 | < .001 | 0.7598 | 1.199 | 1 | |
| speed | with | speed | 0.3837 | 0.0862 | 4.451 | < .001 | 0.2148 | 0.5527 | 1 | |
| visual | with | textual | 0.4082 | 0.0735 | 5.552 | < .001 | 0.2641 | 0.5523 | 0.4585 | |
| visual | with | speed | 0.2622 | 0.0563 | 4.660 | < .001 | 0.1519 | 0.3725 | 0.4705 | |
| textual | with | speed | 0.1735 | 0.0493 | 3.518 | < .001 | 0.0768 | 0.2701 | 0.2830 |
Model fit
| Measure | Value |
|---|---|
| χ² | 85.306 |
| df | 24 |
| p | 8.503e-9 |
| CFI | 0.9306 |
| TLI | 0.8958 |
| RMSEA | 0.0921 |
| RMSEA 90% CI low | 0.0714 |
| RMSEA 90% CI high | 0.1137 |
| SRMR | 0.0652 |
| Log-likelihood | −3737.74 |
| AIC | 7517.49 |
| BIC | 7595.34 |
Variance explained (R²)
| Variable | R² |
|---|---|
| x1 | 0.5958 |
| x2 | 0.1794 |
| x3 | 0.3377 |
| x4 | 0.7252 |
| x5 | 0.7311 |
| x6 | 0.7023 |
| x7 | 0.3243 |
| x8 | 0.5228 |
| x9 | 0.4422 |
Modification indices (largest, MI > 3.84)
| MI | Expected change | Standardized change | |||
|---|---|---|---|---|---|
| visual | measured by | x9 | 36.411 | 0.5770 | 0.5152 |
| x7 | with | x8 | 34.145 | 0.5364 | 0.8592 |
| visual | measured by | x7 | 18.631 | −0.4219 | −0.3489 |
| x8 | with | x9 | 14.946 | −0.4231 | −0.8052 |
| textual | measured by | x3 | 9.151 | −0.2716 | −0.2381 |
| x2 | with | x7 | 8.918 | −0.1827 | −0.1919 |
| textual | measured by | x1 | 8.903 | 0.3503 | 0.2975 |
| x2 | with | x3 | 8.532 | 0.2182 | 0.2231 |
| x3 | with | x5 | 7.858 | −0.1301 | −0.2119 |
| visual | measured by | x5 | 7.441 | −0.2099 | −0.1466 |
| x1 | with | x9 | 7.335 | 0.1379 | 0.2473 |
| x4 | with | x6 | 6.221 | −0.2348 | −0.6458 |
| x4 | with | x7 | 5.920 | 0.0982 | 0.1802 |
| x1 | with | x7 | 5.420 | −0.1291 | −0.1949 |
| x7 | with | x9 | 5.183 | −0.1867 | −0.2775 |
| textual | measured by | x9 | 4.796 | 0.1384 | 0.1360 |
| visual | measured by | x8 | 4.295 | −0.2104 | −0.1872 |
| x3 | with | x9 | 4.126 | 0.1017 | 0.1470 |
Reliability and convergent validity
| Factor | Indicators | ω | AVE |
|---|---|---|---|
| visual | 3 | 0.6253 | 0.3710 |
| textual | 3 | 0.8852 | 0.7195 |
| speed | 3 | 0.6878 | 0.4298 |
- Maximum likelihood (normal likelihood, covariances with divisor N), expected-information standard errors, 74 Fisher-scoring iterations. Free parameters follow lavaan's sem(fixed.x = FALSE) defaults: first loadings fixed to 1, all variances free, exogenous variables and pure outcomes covary.
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 factors3_hs · variables: x1, x2, x3, x4, x5, x6, x7, x8, x9
- Hs labels residuals3_hs · variables: x1, x2, x3, x4, x5, x6, x7, x8, x9
- Poldem sems3_poldem · variables: y1, y2, y3, y4, y5, y6, y7, y8, x1, x2, x3
- Twofactor std lv spaces3_twofactor · variables: anx_1, anx_2, anx_3, anx 4, mood_1, mood_2, mood_3, mood_4
- Path observeds3_hs · variables: x1, x4, x7, x9
- Degenerate constants3_hs · variables: x1, x2, x3, x4, x5, x6, x7, x8, x9
- Degenerate all nas3_hs · variables: x1, x2, x3, x4, x5, x6, x7, x8, x9
- Degenerate empty after filters3_hs · variables: x1, x2, x3, x4, x5, x6, x7, x8, x9
In the guides
Where it sits in the decision guides
- Model selection and structure (penalized, stepwise, SEM) · Statistics Guide · D — Predict an outcome
- Internal consistency: Cronbach's α, ω · Statistics Guide · G — Agreement / reliability
What you need
- Observed variablesnumeric · 2–300 columns
- The observed variables the model may use. In the model syntax, names use letters, digits, dots and underscores — any other character (a space) becomes an underscore. Rows missing a variable the model uses are left out.
Choices you make
model
- Model (lavaan syntax)default —
One statement per line, e.g. visual =~ x1 + x2 + x3 (a factor measured by three items), y ~ x1 + x2 (a regression), x1 ~~ x2 (a residual covariance). The first loading of each factor is fixed to 1; 1*x fixes, NA*x frees, a*x sets equality labels.
hypothesis
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
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
ML estimates and fit indices need enough cases — often 200 or 5–10 per parameter.
Identification
The model needs non-negative degrees of freedom and a scale for each factor.
Proper solution
Negative variances or correlations above 1 (Heywood cases) signal a misspecified model.
Model fit
Common guidelines: CFI and TLI ≥ .95, RMSEA ≤ .06, SRMR ≤ .08 (Hu & Bentler 1999).
Local fit
A modification index above 10 together with a standardized expected change above 0.2 marks a parameter the model leaves out that would change it noticeably. Add one only when theory supports it.
Convergence
The estimation reached its tolerance; estimates from a run that stopped early are unreliable.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- npar
- How many coefficients the model estimated, counting the intercept.
- 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.
- pvalue
- How surprising your data would be if the null hypothesis were true, as a probability.
- cfi
- 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.
- rmsea
- Summaries of how well a factor or structural model reproduces the data's covariances, such as CFI, TLI, RMSEA and SRMR.
- rmsea_low
- A range of effect values compatible with your data at the chosen confidence level.
- rmsea_high
- A range of effect values compatible with your data at the chosen confidence level.
- srmr
- Summaries of how well a factor or structural model reproduces the data's covariances, such as CFI, TLI, RMSEA and SRMR.
- loglik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- aic
- A model score balancing fit against complexity; lower is better, and only differences matter.
- bic
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- baseline_chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- baseline_df
- How much independent information is left to estimate variability after fitting the model.
- max_mi
- The biggest drop in chi-square if one fixed parameter were freed; above 10 with a standardized change over 0.2 suggests misfit.
- max_abs_resid_cor
- The biggest gap between an observed and a model-implied correlation; above 0.1 points to a pair the model fits poorly.
Per group, level or term: est[<parameter>], se[<parameter>], z[<parameter>], std[<parameter>], r2[<variable>], mi[<parameter>], epc[<parameter>], sepc[<parameter>], resid_cor[<pair>], omega[<factor>], ave[<factor>]
Python and R
Python and R agree within simulation error (relative tolerance 1e-5). Python uses pandas, numpy, scipy, codesplash; R uses lavaan, nanoparquet, codesplashr.
Default traps between the two languages
- R fits the model with lavaan::sem(fixed.x = FALSE) — nlminb, then a Gauss–Newton polish from its solution — and Python with the twin codesplash.stats.measurement.cfa (Fisher scoring to 1e-12 with lavaan's rules for free parameters). Both reach the same optimum: χ² agrees to about 1e-11 (the twin's is never larger), and estimates and standard errors to about 1e-6 — up to a few 1e-6 for parameters in nearly flat directions of the likelihood (residual covariances), where lavaan's optimizers stop earlier; hence the P2 band of 1e-5. Fit indices follow lavaan's definitions (normal likelihood with divisor N, RMSEA with N, Bentler's SRMR, baseline model with free covariances among exogenous covariates) and standardized values lavaan's std.all (residual covariances as residual correlations).
- semopy is Python's usual SEM package, but its defaults (a Wishart likelihood, other identification rules) differ from lavaan's, so the twin follows lavaan.
- Modification indices: R reads lavaan::modindices (expected information, equality labels ignored), the twin codesplash.stats.measurement_fit.cfa_modindices computes the same score test (MI = n·g²/(2V), EPC = −g/V) over lavaan's candidate set (lav_pt_full) and standardizes the EPC like sepc.all. A score test magnifies the few-1e-6 differences in nearly flat directions (and, with equality labels, lavaan's augmented-information inverse), so MIs and expected changes agree to about 1e-4 absolute (Political Democracy) and carry their own band; both engines drop MIs below 1e-4, which are equivalent parameters or no change. Residual correlations are sample minus model-implied correlations; ω uses the model-implied total variance of a factor's indicators and AVE the mean squared standardized loading, both from each engine's estimates.
The exact script CodeSplash ran for example “Hs three factor” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Confirmatory factor analysis and structural equation models
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.cfa 1.1.0 · spec 1d38eee718441c4e
# 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 re
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import measurement as ms # ML CFA / SEM with lavaan's defaults (R fits lavaan::sem)
from codesplash.stats import measurement_fit as mf # modification indices, residual correlations, ω and AVE (R: lavaan)
# semopy (semopy.Model(model).fit(data)) is Python's usual SEM package, but its default likelihood
# (Wishart) and identification rules differ from lavaan's; the twin follows lavaan so both engines agree.
# %% Data (names in the model use letters, digits, dots and underscores)
variables = ["x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"]
df = pd.read_parquet("tests/parity/fixtures/s3_hs.parquet", columns=variables)
safe = [re.sub(r"[^A-Za-z0-9._]", "_", v) for v in variables]
if len(set(safe)) < len(safe):
raise ValueError("Two variables have the same name once spaces and symbols become underscores; rename one")
warnings = []
model = "visual =~ x1 + x2 + x3\ntextual =~ x4 + x5 + x6\nspeed =~ x7 + x8 + x9"
if not model.strip():
raise ValueError("Write the model in lavaan syntax, e.g. visual =~ x1 + x2 + x3")
conf = 0.95
# %% Checks on the model's observed variables (in role order) before fitting
model_ov = ms.build_model(ms.parse_model(model), safe)["ov"]
check = [v for v, name in zip(variables, safe) if name in model_ov]
for v in check:
if df[v].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=v)
complete = df[check].dropna() # the rows the fit uses (listwise over the model's variables)
if not len(complete):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(complete, check)
if len(complete) <= len(check): # the sample covariance matrix needs more cases than observed variables
cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"A model with {len(check)} observed variables", min=len(check) + 1, n=len(complete))
for v in check:
if complete[v].nunique() < 2:
cs.cs_error("CS_E_CONSTANT", column=v)
# %% Fit (maximum likelihood, normal likelihood with divisor N, expected-information SEs)
res = ms.cfa(model, df.to_numpy(dtype=float), safe, conf)
if res["n_dropped"]:
warnings.append(f"{res['n_dropped']} of {len(df)} rows were left out because a model variable was missing.")
if not res["converged"]:
warnings.append(f"Estimation did not converge in {res['iterations']} iterations; the estimates are unreliable.")
vars_order = res["model"]["vars"]
order = {v: i for i, v in enumerate(vars_order)}
def key(row):
lhs, op, rhs = row["lhs"], row["op"], row["rhs"]
if op == "~~" and lhs != rhs and order[lhs] > order[rhs]:
lhs, rhs = rhs, lhs # canonical order: observed (role order), then factors (definition order)
return f"{lhs}{op}{rhs}"
nan = lambda v: None if v is None or not np.isfinite(v) else float(v) # noqa: E731
df_model = res["df"]
values = {"n": float(res["n"]), "npar": float(res["npar"]), "chi2": res["chi2"], "df": df_model, "pvalue": nan(res["pvalue"]),
"cfi": res["cfi"], "tli": nan(res["tli"]), "rmsea": nan(res["rmsea"]), "rmsea_low": nan(res["rmsea_low"]),
"rmsea_high": nan(res["rmsea_high"]), "srmr": res["srmr"], "loglik": res["loglik"], "aic": res["aic"], "bic": res["bic"],
"baseline_chi2": res["baseline_chi2"], "baseline_df": res["baseline_df"]}
for row in res["rows"]:
k = key(row)
values[f"est[{k}]"] = row["est"]
values[f"std[{k}]"] = row["std"]
if row["free"]:
values[f"se[{k}]"] = row["se"]
values[f"z[{k}]"] = row["z"]
for v, r2 in res["r2"].items():
values[f"r2[{v}]"] = r2
# %% Local fit and reliability: modification indices with expected changes (lavaan's modindices()),
# residual correlations (sample minus model-implied), McDonald's ω and the average variance extracted
diag = mf.cfa_diagnostics(res)
values.update(diag["values"])
# %% Assumptions
neg = [f"{r['lhs']}" for r in res["rows"] if r["op"] == "~~" and r["lhs"] == r["rhs"] and r["est"] < 0]
over = [key(r) for r in res["rows"] if abs(r["std"]) > 1 + 1e-9]
q = len(res["model"]["ov"])
good = df_model > 0 and res["cfi"] >= 0.95 and res["rmsea"] <= 0.06 and res["srmr"] <= 0.08
assumptions = [
{"key": "sample_size", "label": "Sample size", "status": "warn" if res["n"] < 200 or res["n"] < 5 * res["npar"] else "pass",
"detail": f"{res['n']} cases for {res['npar']} free parameters" + (" — estimates and fit indices may be unstable." if res["n"] < 200 or res["n"] < 5 * res["npar"] else ".")},
{"key": "identification", "label": "Identification", "status": "pass" if df_model > 0 else "info",
"detail": f"{df_model:.0f} degrees of freedom ({q * (q + 1) // 2} variances and covariances, {res['npar']} free parameters)"
+ (" — a saturated model fits perfectly by construction." if df_model == 0 else ".")},
{"key": "proper_solution", "label": "Proper solution", "status": "fail" if neg or over else "pass",
"detail": ("Negative variance: " + ", ".join(neg) + ". " if neg else "") + ("Standardized value above 1: " + ", ".join(over) + "." if over else "")
or "Every variance is positive and every standardized value lies within ±1."},
{"key": "fit", "label": "Model fit", "status": "pass" if good else ("info" if df_model == 0 else "warn"),
"detail": f"CFI {res['cfi']:.3f}, TLI {values['tli'] if values['tli'] is None else round(values['tli'], 3)}, RMSEA {values['rmsea'] if values['rmsea'] is None else round(values['rmsea'], 3)}, SRMR {res['srmr']:.3f}"
+ (" — within Hu & Bentler's guidelines." if good else ".")},
*diag["assumptions"], # local fit (MI > 10 with |standardized change| > 0.2) and convergence
]
# %% Result
pct = f"{conf:.0%}"
labels = {"=~": "measured by", "~": "regressed on", "~~": "with"}
rows = [{"lhs": r["lhs"], "op": labels[r["op"]], "rhs": r["rhs"], "label": r["label"] or "", "est": r["est"], "se": nan(r["se"]),
"z": nan(r["z"]), "p": nan(r["p"]), "ci_low": nan(r["ci_low"]), "ci_high": nan(r["ci_high"]), "std": r["std"]} for r in res["rows"]]
tables = [{"key": "parameters", "title": "Parameter estimates", "columns": [
{"key": "lhs", "label": "", "type": "string"}, {"key": "op", "label": "", "type": "string"}, {"key": "rhs", "label": "", "type": "string"},
{"key": "label", "label": "Label", "type": "string"}, {"key": "est", "label": "Estimate", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"},
{"key": "std", "label": "Standardized", "type": "number"}], "rows": rows},
{"key": "fit", "title": "Model fit", "columns": [{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"measure": m, "value": values[k]} for m, k in [("χ²", "chi2"), ("df", "df"), ("p", "pvalue"), ("CFI", "cfi"), ("TLI", "tli"), ("RMSEA", "rmsea"),
("RMSEA 90% CI low", "rmsea_low"), ("RMSEA 90% CI high", "rmsea_high"), ("SRMR", "srmr"),
("Log-likelihood", "loglik"), ("AIC", "aic"), ("BIC", "bic")]]}]
if res["r2"]:
tables.append({"key": "r2", "title": "Variance explained (R²)", "columns": [{"key": "variable", "label": "Variable", "type": "string"},
{"key": "r2", "label": "R²", "type": "number"}],
"rows": [{"variable": v, "r2": r2} for v, r2 in res["r2"].items()]})
tables += diag["tables"]
charts = []
lv = res["model"]["lv"]
meas = [r for r in res["rows"] if r["op"] == "=~"]
if meas:
inds = list(dict.fromkeys(r["rhs"] for r in meas))
grid = {(r["rhs"], r["lhs"]): r["std"] for r in meas}
cells = [(i, f) for i in inds for f in lv]
charts.append(cs.chart("loadings", "matrix-heatmap", "Standardized loadings", {
"row": cs.col("Indicator", [i for i, _ in cells], "categorical", levels=inds),
"col": cs.col("Factor", [f for _, f in cells], "categorical", levels=lv),
"value": cs.col("Loading", [grid.get(c, 0.0) for c in cells], "numeric"),
"label": cs.col("Text", [f"{grid[c]:.2f}" if c in grid else "" for c in cells], "categorical"),
}, controls={"scale": "diverging"}))
ov, rc = diag["ov"], diag["resid"]
pairs = [(i, j) for i in range(len(ov)) for j in range(len(ov))]
charts.append(cs.chart("residuals", "matrix-heatmap", "Residual correlations (sample − model)", {
"row": cs.col("Variable", [ov[i] for i, _ in pairs], "categorical", levels=ov),
"col": cs.col("With", [ov[j] for _, j in pairs], "categorical", levels=ov),
"value": cs.col("Residual correlation", [0.0 if i == j else float(rc[i, j]) for i, j in pairs], "numeric"),
"label": cs.col("Text", ["" if i == j else f"{rc[i, j]:.2f}" for i, j in pairs], "categorical"),
}, controls={"scale": "diverging"}))
cs.publish({
"method": "measurement.cfa",
"methodVersion": "1.1.0",
"title": "Structural equation model" if any(r["op"] == "~" for r in res["rows"]) else "Confirmatory factor analysis",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(res["n"]),
"summary": f"χ²({df_model:.0f}) = {res['chi2']:.2f}" + (f", {cs.fmt_p(res['pvalue'])}" if values["pvalue"] is not None else "")
+ f"; CFI {res['cfi']:.3f}" + (f", RMSEA {res['rmsea']:.3f}" if values["rmsea"] is not None else "") + f", SRMR {res['srmr']:.3f} ({res['n']} cases).",
"apa": f"χ²({df_model:.0f}, N = {res['n']}) = {cs.fmt_num(res['chi2'])}" + (f", {cs.fmt_p(res['pvalue'])}" if values["pvalue"] is not None else "")
+ f", CFI = {cs.fmt_num(res['cfi'], 2, leading_zero=False)}" + (f", RMSEA = {cs.fmt_num(res['rmsea'], 3, leading_zero=False)}" if values["rmsea"] is not None else "")
+ f", SRMR = {cs.fmt_num(res['srmr'], 3, leading_zero=False)}",
"statistics": [{"key": "chi2", "label": "χ²", "value": res["chi2"]}, {"key": "df", "label": "df", "value": df_model},
{"key": "cfi", "label": "CFI", "value": res["cfi"]}, {"key": "rmsea", "label": "RMSEA", "value": values["rmsea"]},
{"key": "srmr", "label": "SRMR", "value": res["srmr"]}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Maximum likelihood (normal likelihood, covariances with divisor N), expected-information standard errors, {res['iterations']} Fisher-scoring iterations. "
"Free parameters follow lavaan's sem(fixed.x = FALSE) defaults: first loadings fixed to 1, all variances free, exogenous variables and pure outcomes covary."],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Hs three factor” · R version 4.5.1 (2025-06-13)
# Confirmatory factor analysis and structural equation models
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.cfa 1.1.0 · spec 1d38eee718441c4e
# 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)
library(lavaan)
# %% Data (names in the model use letters, digits, dots and underscores)
variables <- c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s3_hs.parquet", col_select = variables))
safe <- gsub("[^A-Za-z0-9._]", "_", variables)
if (anyDuplicated(safe)) stop("Two variables have the same name once spaces and symbols become underscores; rename one")
names(df) <- safe
warnings <- list()
model <- "visual =~ x1 + x2 + x3\ntextual =~ x4 + x5 + x6\nspeed =~ x7 + x8 + x9"
if (!nzchar(trimws(model))) stop("Write the model in lavaan syntax, e.g. visual =~ x1 + x2 + x3")
conf <- 0.95
# %% Checks on the model's observed variables (in role order) before fitting
model_ov <- lavaan::lavNames(lavaan::lavaanify(model), "ov")
check <- which(safe %in% model_ov)
for (j in check) {
if (all(is.na(df[[j]]))) cs_error("CS_E_ALL_MISSING", column = variables[j])
}
complete <- df[stats::complete.cases(df[check]), check, drop = FALSE] # the rows the fit uses (listwise over the model's variables)
names(complete) <- variables[check]
if (nrow(complete) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(complete, variables[check])
if (nrow(complete) <= length(check)) {
# the sample covariance matrix needs more cases than observed variables
cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("A model with %d observed variables", length(check)), min = length(check) + 1, n = nrow(complete))
}
for (v in variables[check]) {
if (length(unique(complete[[v]])) < 2) cs_error("CS_E_CONSTANT", column = v)
}
# %% Fit (maximum likelihood, normal likelihood with divisor N, expected-information SEs)
fit <- lavaan::sem(model, data = df, fixed.x = FALSE)
# nlminb stops at a relative objective change of 1e-10; a Gauss-Newton polish from its solution
# reaches the optimum to ~1e-10 so R and Python agree.
polished <- tryCatch(lavaan::sem(model, data = df, fixed.x = FALSE, start = fit, optim.method = "GN",
control = list(gn.iter.max = 500, gn.tol.x = 1e-14)),
error = function(e) NULL, warning = function(w) NULL)
if (!is.null(polished) && lavaan::lavInspect(polished, "converged")) fit <- polished
if (!lavaan::lavInspect(fit, "converged")) warnings <- c(warnings, "Estimation did not converge; the estimates are unreliable.")
n <- lavaan::lavInspect(fit, "nobs")
n_dropped <- nrow(df) - n
if (n_dropped > 0) warnings <- c(warnings, sprintf("%d of %d rows were left out because a model variable was missing.", n_dropped, nrow(df)))
fm <- lavaan::fitMeasures(fit, c("npar", "chisq", "df", "pvalue", "cfi", "tli", "rmsea", "rmsea.ci.lower", "rmsea.ci.upper", "srmr",
"logl", "aic", "bic", "baseline.chisq", "baseline.df"))
fm <- stats::setNames(as.numeric(fm), names(fm))
pe <- lavaan::parameterEstimates(fit, standardized = TRUE, level = conf)
pe <- pe[pe$op %in% c("=~", "~", "~~"), ]
ov <- safe[safe %in% lavaan::lavNames(fit, "ov")]
lv <- lavaan::lavNames(fit, "lv")
ord <- stats::setNames(seq_along(c(ov, lv)), c(ov, lv))
key <- function(lhs, op, rhs) {
if (op == "~~" && lhs != rhs && ord[[lhs]] > ord[[rhs]]) { tmp <- lhs; lhs <- rhs; rhs <- tmp } # canonical order
paste0(lhs, op, rhs)
}
df_model <- fm[["df"]]
na_if_sat <- function(v) if (df_model > 0 && is.finite(v)) v else NA
values <- list(n = n, npar = fm[["npar"]], chi2 = fm[["chisq"]], df = df_model, pvalue = na_if_sat(fm[["pvalue"]]), cfi = fm[["cfi"]],
tli = na_if_sat(fm[["tli"]]), rmsea = na_if_sat(fm[["rmsea"]]), rmsea_low = na_if_sat(fm[["rmsea.ci.lower"]]),
rmsea_high = na_if_sat(fm[["rmsea.ci.upper"]]), srmr = fm[["srmr"]], loglik = fm[["logl"]], aic = fm[["aic"]], bic = fm[["bic"]],
baseline_chi2 = fm[["baseline.chisq"]], baseline_df = fm[["baseline.df"]])
free <- !is.na(pe$z)
for (i in seq_len(nrow(pe))) {
k <- key(pe$lhs[i], pe$op[i], pe$rhs[i])
values[[sprintf("est[%s]", k)]] <- pe$est[i]
values[[sprintf("std[%s]", k)]] <- pe$std.all[i]
if (free[i]) {
values[[sprintf("se[%s]", k)]] <- pe$se[i]
values[[sprintf("z[%s]", k)]] <- pe$z[i]
}
}
r2 <- lavaan::lavInspect(fit, "r2")
for (v in names(r2)) values[[sprintf("r2[%s]", v)]] <- unname(r2[[v]])
# %% Local fit and reliability: modification indices with expected changes (lavaan::modindices),
# residual correlations (sample minus model-implied), McDonald's ω and the average variance extracted
mi <- tryCatch(suppressWarnings(lavaan::modindices(fit)), error = function(e) NULL) # ignores equality labels, like the twin
# An MI below 1e-4 is an equivalent parameter or no change; lavaan's rounding can leave such rows (the twin drops them too).
mi <- if (is.null(mi)) data.frame() else mi[mi$op %in% c("=~", "~", "~~") & is.finite(mi$mi) & mi$mi >= 1e-4, , drop = FALSE]
for (i in seq_len(nrow(mi))) {
k <- key(mi$lhs[i], mi$op[i], mi$rhs[i])
values[[sprintf("mi[%s]", k)]] <- mi$mi[i]
values[[sprintf("epc[%s]", k)]] <- mi$epc[i]
values[[sprintf("sepc[%s]", k)]] <- if (is.finite(mi$sepc.all[i])) mi$sepc.all[i] else NA
}
values$max_mi <- if (nrow(mi)) max(mi$mi) else NA
S_obs <- lavaan::lavInspect(fit, "sampstat")$cov
S_mod <- lavaan::lavInspect(fit, "implied")$cov
rc <- stats::cov2cor(S_obs[ov, ov]) - stats::cov2cor(S_mod[ov, ov])
big <- NULL
for (a in seq_len(length(ov) - 1)) for (b in (a + 1):length(ov)) {
values[[sprintf("resid_cor[%s]", key(ov[a], "~~", ov[b]))]] <- rc[a, b]
if (is.null(big) || abs(rc[a, b]) > abs(rc[big[1], big[2]])) big <- c(a, b)
}
values$max_abs_resid_cor <- if (is.null(big)) NA else abs(rc[big[1], big[2]])
cov_lv <- if (length(lv)) lavaan::lavInspect(fit, "cov.lv") else NULL
rel <- list()
for (f in lv) {
lr <- pe[pe$op == "=~" & pe$lhs == f, , drop = FALSE]
if (nrow(lr) < 2 || !all(lr$rhs %in% ov)) next
total <- sum(S_mod[lr$rhs, lr$rhs])
omega <- if (total > 0) sum(lr$est)^2 * cov_lv[f, f] / total else NA
rel[[length(rel) + 1]] <- list(factor = f, k = nrow(lr), omega = omega, ave = mean(lr$std.all^2))
values[[sprintf("omega[%s]", f)]] <- omega
values[[sprintf("ave[%s]", f)]] <- mean(lr$std.all^2)
}
oplab_mi <- c("=~" = "measured by", "~" = "regressed on", "~~" = "with")
mi_sorted <- if (nrow(mi)) mi[order(-mi$mi), , drop = FALSE] else mi
flag <- mi_sorted[mi_sorted$mi > 10 & is.finite(mi_sorted$sepc.all) & abs(mi_sorted$sepc.all) > 0.2, , drop = FALSE] # owner decision 11
tail_rc <- if (is.null(big)) "" else sprintf(" Largest residual correlation: %s with %s (r = %.3f).", ov[big[1]], ov[big[2]], rc[big[1], big[2]])
local_fit <- if (!nrow(mi)) {
list(key = "local_fit", label = "Local fit", status = "info",
detail = paste0("No parameter can be added (the model is saturated or the information matrix is singular).", tail_rc))
} else if (nrow(flag)) {
shown <- utils::head(flag, 6)
list(key = "local_fit", label = "Local fit", status = "warn",
detail = paste0("MI above 10 with a standardized change above 0.2: ",
paste(sprintf("%s %s %s (MI %.1f, %+.2f)", shown$lhs, oplab_mi[shown$op], shown$rhs, shown$mi, shown$sepc.all), collapse = "; "),
if (nrow(flag) > 6) " …" else "", ".", tail_rc))
} else {
list(key = "local_fit", label = "Local fit", status = "pass",
detail = paste0(sprintf("No modification index above 10 comes with a standardized change above 0.2 (largest MI %.2f).", values$max_mi), tail_rc))
}
converged <- lavaan::lavInspect(fit, "converged")
convergence <- list(key = "convergence", label = "Convergence", status = if (converged) "pass" else "warn",
detail = if (converged) "lavaan's optimizer converged." else "lavaan's optimizer stopped without converging; the estimates are unreliable.")
# %% Assumptions
vars <- pe$op == "~~" & pe$lhs == pe$rhs
neg <- pe$lhs[vars & pe$est < 0]
over <- vapply(which(abs(pe$std.all) > 1 + 1e-9), function(i) key(pe$lhs[i], pe$op[i], pe$rhs[i]), character(1))
q <- length(ov)
small <- n < 200 || n < 5 * fm[["npar"]]
good <- df_model > 0 && fm[["cfi"]] >= 0.95 && fm[["rmsea"]] <= 0.06 && fm[["srmr"]] <= 0.08
fmt3 <- function(v) if (is.na(v)) "None" else sprintf("%.3f", v)
proper <- paste0(if (length(neg)) paste0("Negative variance: ", paste(neg, collapse = ", "), ". ") else "",
if (length(over)) paste0("Standardized value above 1: ", paste(over, collapse = ", "), ".") else "")
assumptions <- list(
list(key = "sample_size", label = "Sample size", status = if (small) "warn" else "pass",
detail = paste0(sprintf("%d cases for %d free parameters", n, fm[["npar"]]), if (small) " — estimates and fit indices may be unstable." else ".")),
list(key = "identification", label = "Identification", status = if (df_model > 0) "pass" else "info",
detail = paste0(sprintf("%.0f degrees of freedom (%d variances and covariances, %d free parameters)", df_model, q * (q + 1) / 2, fm[["npar"]]),
if (df_model == 0) " — a saturated model fits perfectly by construction." else ".")),
list(key = "proper_solution", label = "Proper solution", status = if (length(neg) || length(over)) "fail" else "pass",
detail = if (nzchar(proper)) proper else "Every variance is positive and every standardized value lies within ±1."),
list(key = "fit", label = "Model fit", status = if (good) "pass" else if (df_model == 0) "info" else "warn",
detail = paste0(sprintf("CFI %.3f, TLI %s, RMSEA %s, SRMR %.3f", fm[["cfi"]], fmt3(values$tli), fmt3(values$rmsea), fm[["srmr"]]),
if (good) " — within Hu & Bentler's guidelines." else ".")),
local_fit, # MI > 10 with |standardized change| > 0.2
convergence
)
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
oplab <- c("=~" = "measured by", "~" = "regressed on", "~~" = "with")
fin <- function(v) if (is.finite(v)) v else NA
rows <- lapply(seq_len(nrow(pe)), function(i) list(
lhs = pe$lhs[i], op = unname(oplab[pe$op[i]]), rhs = pe$rhs[i], label = pe$label[i], est = pe$est[i],
se = if (free[i]) pe$se[i] else NA, z = if (free[i]) pe$z[i] else NA, p = if (free[i]) pe$pvalue[i] else NA,
ci_low = if (free[i]) pe$ci.lower[i] else NA, ci_high = if (free[i]) pe$ci.upper[i] else NA, std = pe$std.all[i]))
fit_rows <- lapply(list(c("χ²", "chi2"), c("df", "df"), c("p", "pvalue"), c("CFI", "cfi"), c("TLI", "tli"), c("RMSEA", "rmsea"),
c("RMSEA 90% CI low", "rmsea_low"), c("RMSEA 90% CI high", "rmsea_high"), c("SRMR", "srmr"),
c("Log-likelihood", "loglik"), c("AIC", "aic"), c("BIC", "bic")), function(m) list(measure = m[1], value = values[[m[2]]]))
tables <- list(
list(key = "parameters", title = "Parameter estimates", columns = list(
list(key = "lhs", label = "", type = "string"), list(key = "op", label = "", type = "string"), list(key = "rhs", label = "", type = "string"),
list(key = "label", label = "Label", type = "string"), list(key = "est", label = "Estimate", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
list(key = "std", label = "Standardized", type = "number")), rows = rows),
list(key = "fit", title = "Model fit", columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = fit_rows)
)
if (length(r2)) {
tables <- c(tables, list(list(key = "r2", title = "Variance explained (R²)", columns = list(
list(key = "variable", label = "Variable", type = "string"), list(key = "r2", label = "R²", type = "number")),
rows = lapply(names(r2), function(v) list(variable = v, r2 = unname(r2[[v]]))))))
}
shown_mi <- utils::head(mi_sorted[mi_sorted$mi > stats::qchisq(0.95, 1), , drop = FALSE], 20)
if (nrow(mi)) {
tables <- c(tables, list(list(key = "modindices", title = "Modification indices (largest, MI > 3.84)", columns = list(
list(key = "lhs", label = "", type = "string"), list(key = "op", label = "", type = "string"), list(key = "rhs", label = "", type = "string"),
list(key = "mi", label = "MI", type = "number"), list(key = "epc", label = "Expected change", type = "number"),
list(key = "sepc", label = "Standardized change", type = "number")),
rows = lapply(seq_len(nrow(shown_mi)), function(i) list(lhs = shown_mi$lhs[i], op = unname(oplab_mi[shown_mi$op[i]]), rhs = shown_mi$rhs[i],
mi = shown_mi$mi[i], epc = shown_mi$epc[i], sepc = fin(shown_mi$sepc.all[i]))))))
}
if (length(rel)) {
tables <- c(tables, list(list(key = "reliability", title = "Reliability and convergent validity", columns = list(
list(key = "factor", label = "Factor", type = "string"), list(key = "k", label = "Indicators", type = "number"),
list(key = "omega", label = "ω", type = "number"), list(key = "ave", label = "AVE", type = "number")),
rows = lapply(rel, function(r) list(factor = r$factor, k = r$k, omega = r$omega, ave = r$ave)))))
}
charts <- list()
meas <- pe[pe$op == "=~", ]
if (nrow(meas)) {
inds <- unique(meas$rhs)
cells <- expand.grid(f = lv, i = inds, stringsAsFactors = FALSE)
val <- vapply(seq_len(nrow(cells)), function(r) { m <- meas$std.all[meas$rhs == cells$i[r] & meas$lhs == cells$f[r]]; if (length(m)) m[1] else NA }, numeric(1))
charts <- list(cs_chart("loadings", "matrix-heatmap", "Standardized loadings", list(
row = cs_col("Indicator", cells$i, "categorical", levels = inds),
col = cs_col("Factor", cells$f, "categorical", levels = lv),
value = cs_col("Loading", ifelse(is.na(val), 0, val), "numeric"),
label = cs_col("Text", ifelse(is.na(val), "", sprintf("%.2f", val)), "categorical")
), controls = list(scale = "diverging")))
}
rcells <- expand.grid(j = seq_along(ov), i = seq_along(ov))
charts <- c(charts, list(cs_chart("residuals", "matrix-heatmap", "Residual correlations (sample − model)", list(
row = cs_col("Variable", ov[rcells$i], "categorical", levels = ov),
col = cs_col("With", ov[rcells$j], "categorical", levels = ov),
value = cs_col("Residual correlation", ifelse(rcells$i == rcells$j, 0, rc[cbind(rcells$i, rcells$j)]), "numeric"),
label = cs_col("Text", ifelse(rcells$i == rcells$j, "", sprintf("%.2f", rc[cbind(rcells$i, rcells$j)])), "categorical")
), controls = list(scale = "diverging"))))
structural <- any(pe$op == "~")
cs_publish(list(
method = "measurement.cfa",
methodVersion = "1.1.0",
title = if (structural) "Structural equation model" else "Confirmatory factor analysis",
engine = cs_engine_info("lavaan", "codesplashr"),
n = n,
summary = paste0(sprintf("χ²(%.0f) = %.2f", df_model, fm[["chisq"]]), if (!is.na(values$pvalue)) paste0(", ", cs_fmt_p(fm[["pvalue"]])) else "",
sprintf("; CFI %.3f", fm[["cfi"]]), if (!is.na(values$rmsea)) sprintf(", RMSEA %.3f", fm[["rmsea"]]) else "",
sprintf(", SRMR %.3f (%d cases).", fm[["srmr"]], n)),
apa = paste0(sprintf("χ²(%.0f, N = %d) = %s", df_model, n, cs_fmt_num(fm[["chisq"]])), if (!is.na(values$pvalue)) paste0(", ", cs_fmt_p(fm[["pvalue"]])) else "",
sprintf(", CFI = %s", cs_fmt_num(fm[["cfi"]], 2, leading_zero = FALSE)),
if (!is.na(values$rmsea)) sprintf(", RMSEA = %s", cs_fmt_num(fm[["rmsea"]], 3, leading_zero = FALSE)) else "",
sprintf(", SRMR = %s", cs_fmt_num(fm[["srmr"]], 3, leading_zero = FALSE))),
statistics = list(list(key = "chi2", label = "χ²", value = fm[["chisq"]]), list(key = "df", label = "df", value = df_model),
list(key = "cfi", label = "CFI", value = fm[["cfi"]]), list(key = "rmsea", label = "RMSEA", value = values$rmsea),
list(key = "srmr", label = "SRMR", value = fm[["srmr"]])),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list("lavaan::sem(fixed.x = FALSE): maximum likelihood (normal likelihood, covariances with divisor N), expected-information standard errors; first loadings fixed to 1, all variances free, exogenous variables and pure outcomes covary."),
charts = charts,
values = values
))
Sources
- Rosseel, Y. (2012). lavaan: An R package for structural equation modeling. Journal of Statistical Software, 48(2), 1–36.
- Bollen, K. A. (1989). Structural equations with latent variables. Wiley.
- Hu, L., & Bentler, P. M. (1999). Cutoff criteria for fit indexes in covariance structure analysis. Structural Equation Modeling, 6, 1–55.
- Sörbom, D. (1989). Model modification. Psychometrika, 54, 371–384.
- Saris, W. E., Satorra, A., & van der Veld, W. M. (2009). Testing structural equation models or detection of misspecifications? Structural Equation Modeling, 16, 561–582.
- McDonald, R. P. (1999). Test theory: A unified treatment. Erlbaum.
- Fornell, C., & Larcker, D. F. (1981). Evaluating structural equation models with unobservable variables and measurement error. Journal of Marketing Research, 18, 39–50.
From the CodeSplash method registry · measurement.cfa v1.1.0.