Skip to content

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.

Verified in Python and R Python and R agree within simulation error

A real result

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

Confirmatory factor analysisRecorded · Python and R agreeRecorded 2026-11-17 · 321 values compared · largest relative difference 9.2e-7
R

χ²(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

Standardized loadingsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
FactorTextIndicatorLoading
visual0.77x10.7719
textualx10
speedx10
visual0.42x20.4236
textualx20
speedx20
visual0.58x30.5811
textualx30
speedx30
visualx40
textual0.85x40.8516
speedx40
visualx50
textual0.86x50.8551
speedx50
visualx60
textual0.84x60.8380
speedx60
visualx70
textualx70
speed0.57x70.5695
visualx80
textualx80
speed0.72x80.7230
visualx90
textualx90
speed0.67x90.6650
Residual correlations (sample − model)What do the values of a square or rectangular result matrix look like at a glance?
View data
WithTextVariableResidual correlation
x1x10
x2-0.03x1−0.0296
x3-0.01x1−0.0079
x40.07x10.0713
x5-0.01x1−0.0092
x60.06x10.0602
x7-0.14x1−0.1400
x8-0.04x1−0.0387
x90.15x10.1488
x1-0.03x2−0.0296
x2x20
x30.09x20.0937
x4-0.01x2−0.0125
x5-0.03x2−0.0267
x60.03x20.0298
x7-0.19x2−0.1892
x8-0.05x2−0.0518
x90.07x20.0735
x1-0.01x3−0.0079
x20.09x30.0937
x3x30
x4-0.07x3−0.0683
x5-0.15x3−0.1506
x6-0.03x3−0.0256
x7-0.08x3−0.0838
x8-0.01x3−0.0117
x90.15x30.1468
x10.07x40.0713
x2-0.01x4−0.0125
x3-0.07x4−0.0683
x4x40
x50.01x40.0050
x6-0.01x4−0.0092
x70.04x40.0366
x8-0.07x4−0.0673
x90.05x40.0476
x1-0.01x5−0.0092
x2-0.03x5−0.0267
x3-0.15x5−0.1506
x40.01x50.0050
x5x50
x60.00x50.0034
x7-0.04x5−0.0358
x8-0.04x5−0.0363
x90.07x50.0666
x10.06x60.0602
x20.03x60.0298
x3-0.03x6−0.0256
x4-0.01x6−0.0092
x50.00x60.0034
x6x60
x7-0.01x6−0.0140
x8-0.02x6−0.0219
x90.06x60.0565
x1-0.14x7−0.1400
x2-0.19x7−0.1892
x3-0.08x7−0.0838
x40.04x70.0366
x5-0.04x7−0.0358
x6-0.01x7−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

LabelEstimateSEzp95% CI low95% CI highStandardized
visualmeasured byx1—1—————0.7719
visualmeasured byx2—0.55350.09975.554< .0010.35820.74880.4236
visualmeasured byx3—0.72940.10916.685< .0010.51550.94320.5811
textualmeasured byx4—1—————0.8516
textualmeasured byx5—1.1130.065417.014< .0010.98491.2410.8551
textualmeasured byx6—0.92610.055416.703< .0010.81751.0350.8380
speedmeasured byx7—1—————0.5695
speedmeasured byx8—1.1800.16507.152< .0010.85661.5030.7230
speedmeasured byx9—1.0820.15127.155< .0010.78521.3780.6650
x1withx1—0.54910.11364.833< .0010.32640.77170.4042
x2withx2—1.1340.101711.146< .0010.93451.3330.8206
x3withx3—0.84430.09069.317< .0010.66671.0220.6623
x4withx4—0.37120.04777.779< .0010.27760.46470.2748
x5withx5—0.44630.05847.642< .0010.33180.56070.2689
x6withx6—0.35620.04308.277< .0010.27190.44050.2977
x7withx7—0.79940.08149.823< .0010.63990.95890.6757
x8withx8—0.48770.07426.573< .0010.34230.63310.4772
x9withx9—0.56610.07078.003< .0010.42750.70480.5578
visualwithvisual—0.80930.14555.564< .0010.52421.0941
textualwithtextual—0.97950.11218.737< .0010.75981.1991
speedwithspeed—0.38370.08624.451< .0010.21480.55271
visualwithtextual—0.40820.07355.552< .0010.26410.55230.4585
visualwithspeed—0.26220.05634.660< .0010.15190.37250.4705
textualwithspeed—0.17350.04933.518< .0010.07680.27010.2830

Model fit

MeasureValue
χ²85.306
df24
p8.503e-9
CFI0.9306
TLI0.8958
RMSEA0.0921
RMSEA 90% CI low0.0714
RMSEA 90% CI high0.1137
SRMR0.0652
Log-likelihood−3737.74
AIC7517.49
BIC7595.34

Variance explained (R²)

VariableR²
x10.5958
x20.1794
x30.3377
x40.7252
x50.7311
x60.7023
x70.3243
x80.5228
x90.4422

Modification indices (largest, MI > 3.84)

MIExpected changeStandardized change
visualmeasured byx936.4110.57700.5152
x7withx834.1450.53640.8592
visualmeasured byx718.631−0.4219−0.3489
x8withx914.946−0.4231−0.8052
textualmeasured byx39.151−0.2716−0.2381
x2withx78.918−0.1827−0.1919
textualmeasured byx18.9030.35030.2975
x2withx38.5320.21820.2231
x3withx57.858−0.1301−0.2119
visualmeasured byx57.441−0.2099−0.1466
x1withx97.3350.13790.2473
x4withx66.220−0.2348−0.6458
x4withx75.9200.09820.1802
x1withx75.420−0.1291−0.1949
x7withx95.183−0.1867−0.2775
textualmeasured byx94.7960.13840.1360
visualmeasured byx84.295−0.2104−0.1872
x3withx94.1260.10170.1470

Reliability and convergent validity

FactorIndicatorsωAVE
visual30.62530.3710
textual30.88520.7195
speed30.68780.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.
Python

χ²(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

LabelEstimateSEzp95% CI low95% CI highStandardized
visualmeasured byx11—————0.7719
visualmeasured byx20.55350.09975.554< .0010.35820.74880.4236
visualmeasured byx30.72940.10916.685< .0010.51550.94320.5811
textualmeasured byx41—————0.8516
textualmeasured byx51.1130.065417.014< .0010.98491.2410.8551
textualmeasured byx60.92610.055416.703< .0010.81751.0350.8380
speedmeasured byx71—————0.5695
speedmeasured byx81.1800.16507.152< .0010.85661.5030.7230
speedmeasured byx91.0820.15127.155< .0010.78521.3780.6650
x1withx10.54910.11364.833< .0010.32640.77170.4042
x2withx21.1340.101711.146< .0010.93451.3330.8206
x3withx30.84430.09069.317< .0010.66671.0220.6623
x4withx40.37120.04777.779< .0010.27760.46470.2748
x5withx50.44630.05847.642< .0010.33180.56070.2689
x6withx60.35620.04308.277< .0010.27190.44050.2977
x7withx70.79940.08149.823< .0010.63990.95890.6757
x8withx80.48770.07426.573< .0010.34230.63310.4772
x9withx90.56610.07078.003< .0010.42750.70480.5578
visualwithvisual0.80930.14555.564< .0010.52421.0941
textualwithtextual0.97950.11218.737< .0010.75981.1991
speedwithspeed0.38370.08624.451< .0010.21480.55271
visualwithtextual0.40820.07355.552< .0010.26410.55230.4585
visualwithspeed0.26220.05634.660< .0010.15190.37250.4705
textualwithspeed0.17350.04933.518< .0010.07680.27010.2830

Model fit

MeasureValue
χ²85.306
df24
p8.503e-9
CFI0.9306
TLI0.8958
RMSEA0.0921
RMSEA 90% CI low0.0714
RMSEA 90% CI high0.1137
SRMR0.0652
Log-likelihood−3737.74
AIC7517.49
BIC7595.34

Variance explained (R²)

VariableR²
x10.5958
x20.1794
x30.3377
x40.7252
x50.7311
x60.7023
x70.3243
x80.5228
x90.4422

Modification indices (largest, MI > 3.84)

MIExpected changeStandardized change
visualmeasured byx936.4110.57700.5152
x7withx834.1450.53640.8592
visualmeasured byx718.631−0.4219−0.3489
x8withx914.946−0.4231−0.8052
textualmeasured byx39.151−0.2716−0.2381
x2withx78.918−0.1827−0.1919
textualmeasured byx18.9030.35030.2975
x2withx38.5320.21820.2231
x3withx57.858−0.1301−0.2119
visualmeasured byx57.441−0.2099−0.1466
x1withx97.3350.13790.2473
x4withx66.221−0.2348−0.6458
x4withx75.9200.09820.1802
x1withx75.420−0.1291−0.1949
x7withx95.183−0.1867−0.2775
textualmeasured byx94.7960.13840.1360
visualmeasured byx84.295−0.2104−0.1872
x3withx94.1260.10170.1470

Reliability and convergent validity

FactorIndicatorsωAVE
visual30.62530.3710
textual30.88520.7195
speed30.68780.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.
Python

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,
})
R

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.