Skip to content

Confirmatory factor analysis and SEM

State a model in lavaan syntax, then see if the data are compatible with it. Read chi-square, CFI, TLI, RMSEA and SRMR together, and be careful with modification indices.

Advanced ~13 min10 steps

What runs in CodeSplash

You will be able to

  • Write a measurement model in lavaan syntax
  • Read several fit indices together, without relying on cut-offs alone
  • Explain the risk of post hoc model modification

Read first

01

You state the model first

Read

In confirmatory factor analysisConfirmatory factor analysisTests a factor structure you stated in advance, including which items load on which factor. you say which items load on which factors, and everything else is fixed at zero. Then you ask if the data are compatible with that.

CodeSplash uses lavaan's model syntax: =~ means "is measured by".

visual  =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed   =~ x7 + x8 + x9

By default, the first loading of each factor is fixed to 1 to set its scale.

02

Predict the verdict

Predict

Predict first

This three-factor model is fitted to 301 schoolchildren. Most researchers consider it a reasonable model.

Its chi-square test asks whether the model reproduces the covariances exactly. What do you expect?

Rejects: p is smallFails to reject: p is large
Reveal

It rejects: χ2\chi^2 = 85.3 on 24 df, p < .001. No simple model is exactly true, and with enough people the test detects that. That's why researchers read approximate fit indices too.

03

Read the fit indices together

Read
IndexHereRough guide
CFI0.931above 0.95 is good
TLI0.896above 0.95 is good
RMSEA0.092 (0.071 to 0.114)below 0.060.06 is good, above 0.100.10 poor
SRMR0.065below 0.080.08 is good

These fit indicesFit indicesSummaries of how well a factor or structural model reproduces the data's covariances, such as CFI, TLI, RMSEA and SRMR. give a mixed picture: SRMR is fine, while CFI, TLI and RMSEA fall short of these guides. The cut-offs aren't laws. They come from particular simulations, so read them with the loadings and the residuals.

04

Read the indices

Checkpoint

Check yourself

With 5,000 respondents, chi-square rejects (p < 0.001), but CFI is 0.98 and RMSEA 0.03. What's the sensible reading?

Show the answer

Answer: b

With a large sample, trivial misfit becomes detectable. Approximate indices tell you how much misfit there is. Still check the residuals.

05

Run it

In the app

Write a model in Model (lavaan syntax). Open the example and try moving an item to a different factor.

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.
The exact R script · R 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
))
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.
The exact Python script · Python 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,
})

A second example fits well: on simulated two-factor data, CFI is 0.996 and RMSEA 0.023, and its chi-square test gives p = .286.

06

From measurement to structure

Read

Add regressions (~) between latent variables and you have a structural equation model. In the classic political democracy example, CFI is 0.997 on 75 countries.

Good fit doesn't make the arrows causal. Many models with different arrow directions fit identically. The causal claim has to come from the design and subject knowledge.

07

What would change your mind?

Reflect

Before you fit a model, write down one other structure that could explain the same correlations, for instance with an arrow reversed. What data could tell the two apart? If none could, how would you word your conclusion?

08

Same model, two dialects

Read
Python
import pandas as pd
import semopy

df = pd.read_csv("s3_hs.csv")
desc = """
visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9
"""
model = semopy.Model(desc)
model.fit(df[[f"x{i}" for i in range(1, 10)]])
print(semopy.calc_stats(model).T)
R
library(lavaan)
df <- read.csv("s3_hs.csv")
fit <- cfa("
  visual =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed =~ x7 + x8 + x9
", data = df)
fitMeasures(fit, c("chisq", "df", "cfi", "tli", "rmsea", "srmr"))
09

Check your understanding

Checkpoint

Check yourself

What lavaan operator means "is measured by"?

Show the answer

Accepted: “=~”

=~ defines a latent variable from its indicators; ~ is a regression; ~~ is a variance or covariance.

Check yourself

A structural model with A → B fits very well. What can you conclude?

Show the answer

Answer: c

Fit doesn't identify direction. Equivalent models with reversed arrows imply the same covariances.

10

Recap

Recap
  • State the model first, then test how compatible the data are with it.
  • Chi-square tests exact fit; read approximate indices together, not against rigid cut-offs.
  • Modifying a model after seeing fit is exploration.
  • Good fit doesn't make arrows causal.

Concepts in this lesson