lavaan and Confirmatory Factor Analysis Knowledge Patch
Use this skill when writing, reviewing, or updating R code for confirmatory
factor analysis and related structural equation models in lavaan. It is
especially relevant for categorical outcomes, robust estimators, multigroup
constraints, multilevel models, missing data, sampling weights, effects, and
diagnostics.
Before changing a fit:
- Inspect the installed lavaan version and the variables' continuous,
ordinal, binary, grouping, cluster, and weight roles.
- Separate estimation choices from test-statistic and standard-error
corrections; similarly named robust estimators do not behave identically.
- Check whether a parameter is fixed, group-constrained, or freely estimated
before selecting a modification-index or score-test workflow.
- Preserve explicit parser, optimizer, and weighting choices when migrating
compatibility-sensitive code.
- Open the topic reference that matches the task and retain exact option,
operator, and parameter-table names.
Reference index
| Reference |
Topics |
| model-syntax-and-estimation.md |
API and parser migration, categorical and robust estimation, instruments, composites, correlations, tuning lists, ESEM targets, and optimization |
| groups-multilevel-and-weights.md |
Multigroup modifiers and equality constraints, sampling weights, two-level least squares, random slopes, missing-data optimization, and level-specific fit |
| inference-effects-and-diagnostics.md |
Missing-data auxiliaries, residuals, effects, structured-after-measurement inference, corrected tests, fit indices, prediction, modification diagnostics, and parameter inspection |
Quick reference: compatibility-sensitive changes
Argument and parser migration
- Prefer
snake_case for user-facing formal arguments. Dotted argument names
remain accepted but are deprecated.
- Option names accept snake case or capital letters.
- The
open syntax parser is now the default. Code that depended on the
previous parser should choose or test parser behavior explicitly.
- The minimum R version is 3.4, and installing lavaan does not require
compilation.
fit <- cfa(model, data = dat, sampling_weights = "weight")
Replaced tuning interfaces
estimator, rotation, and bootstrap may each be a list; use these in
place of their separate *.args arguments.
optim_method = "gn" now means Levenberg-Marquardt damped Fisher scoring,
and its controls belong in gn_args.
- Composite models using
<~ have an analytic gradient. Remove the obsolete
optim_gradient = "numerical" workaround.
- For ESEM, assign a named list of target matrices to
rotation_args$target to provide one target per EFA block.
Fit-index naming
fitMeasures() reports the Maydeu-Olivares et al. GFI under the usual GFI
name.
- Request
gfi_lisrel or agfi_lisrel when downstream code intends the
previously named GFI or AGFI statistics.
Quick reference: categorical and robust estimation
Categorical endogenous variables
- lavaan supports binary and ordinal endogenous variables, not nominal ones.
- Pass selected variables with
ordered = c(...), or use ordered = TRUE
for all endogenous variables.
- This automatically selects WLSMV: parameter estimation uses DWLS, while
robust standard errors and the mean-and-variance-adjusted test use the full
weight matrix.
- ULSMV and PML are alternatives. FIML is not supported for this categorical
workflow.
fit <- cfa(model, data = dat, ordered = c("item1", "item2"))
Robust continuous-data variants
MLM uses a Satorra-Bentler test, MLMVS a Satterthwaite
mean-and-variance adjustment, and MLMV a scale-shifted adjustment. These
three require complete data.
MLF combines first-derivative standard errors with a conventional test.
MLR combines Huber-White standard errors with an asymptotic Yuan-Bentler
test. Both MLF and MLR support complete or incomplete data.
- Less-common choices include distributionally weighted least squares
(
DLS) and pairwise maximum likelihood (PML).
- Robust DWLS and ULS variants estimate parameters with the diagonal weight
matrix but use the full matrix for standard-error and test corrections.
fit <- cfa(model, data = dat, estimator = "MLR", missing = "ML")
Quick reference: syntax and structural choices
External instruments
Use |~ to declare external instruments and estimator = "IV" to select
MIIV-2SLS.
model <- '
y ~ x
y |~ z1 + z2
'
fit <- sem(model, data = dat, estimator = "IV")
The IV implementation handles multiple groups, categorical data, simple
equality constraints, two-stage missing data, user-specified instruments,
and Sargan/Hansen overidentification tests.
Model composition and covariance structure
- Pass a character vector directly as
model to combine reusable or
conditional syntax fragments.
- A character vector supplied to
correlation requests a partial-correlation
structure and can be combined with fixed_x = TRUE.
auto_cov_x = TRUE freely estimates covariances between latent and observed
exogenous variables; its default is FALSE.
- Composites support a robust mean structure, higher-order factors,
multilevel models, and the
composites_cov option.
- Reduced-bias M-estimation is available as an initial framework for reducing
finite-sample bias.
Quick reference: groups, levels, and weights
Multigroup constraints
- In multigroup syntax,
c(...) supplies one value or label per group.
- Repeat a label to impose equality. Use
NA at a group position to leave
that group's parameter free while another group's value is fixed.
group_equal applies supported classes of equality constraints in bulk;
group_partial names exceptions in model syntax.
modindices() only considers parameters fixed to zero. Use
lavTestScore() to assess release of equality constraints.
fit <- cfa(
model, data = dat, group = "school",
group_equal = c("loadings", "intercepts"),
group_partial = c("visual=~x2", "x7~1")
)
Two-level models
- Two-level models can use DWLS and WLS, including WLSMV for categorical
data; handle exogenous covariates with
fixed_x and conditional_x.
rv() adds random slopes to continuous two-level models. Supported paths
include ML through nlminb or EM, MLR standard errors, empirical-Bayes
predictions, and complete data or missing = "ml".
- With ML missing-data handling, EM is the default two-level optimizer. It
supports SQUAREM or quasi-Newton acceleration and analytic Louis observed
information.
- Summaries can show level-specific fit based on partially saturated models.
Request a level through
fitMeasures(fit, level = ...) and control the
behavior with fit_by_level.
Sampling weights
- Use
sampling_weights_type to distinguish design weights from frequency
weights.
- Weights are normalized within group by default.
- Least-squares estimators use a properly weighted Gamma/NACOV matrix.
Quick reference: missing data and inference
Auxiliary and conditional variables
- Supply missing-data auxiliary variables through
aux.
- For continuous single-level models, FIML, two-stage, and robust-two-stage
missing-data handling support
conditional_x = TRUE, including standard
errors and the corresponding Gamma/NACOV matrix.
Effects and test statistics
lavEffects() computes total, indirect, and direct effects with
delta-method, Monte Carlo, or bootstrap standard errors.
- For parameters defined with
:=, use se_def = "mc" for Monte Carlo
standard errors and confidence intervals; se_delta_second_order enables
the second-order delta option.
- Foldnes-Moss-Gronneberg statistics are available. Select the Hayakawa
variants with
test = "mean.var.adjusted.corrected" or
test = "scaled.shifted.corrected".
- With a robust estimator,
lavTestScore() and lavTestWald() report scaled,
adjusted, and robust statistics.
Residuals, prediction, and inspection
lavResiduals(output = "text") can display largest-residual tables and
supplies elementwise residual standard errors and z-tests. It also supports
conditional_x, multilevel models, and a supplied saturated model via h1.
lavPredict() can return standard errors for categorical factor scores and
accepts newdata for two-level models.
- The
mdist casewise Mahalanobis-distance diagnostics in lavPredict() and
lavInspect() support categorical and ordered data.
- With no
what, lavInspect() returns model matrices whose nonzero integers
identify free parameters. Use what = "start" for starting-value matrices
and what = "list" for the full parameter table returned by
parTable(fit).
Use the references for complete option sets, supported combinations, and
diagnostic distinctions before editing production analyses.
1---2name: lavaan-cfa-knowledge-patch3description: lavaan / CFA4license: MIT5---678# lavaan and Confirmatory Factor Analysis Knowledge Patch910Use this skill when writing, reviewing, or updating R code for confirmatory11factor analysis and related structural equation models in lavaan. It is12especially relevant for categorical outcomes, robust estimators, multigroup13constraints, multilevel models, missing data, sampling weights, effects, and14diagnostics.1516Before changing a fit:17181. Inspect the installed lavaan version and the variables' continuous,19 ordinal, binary, grouping, cluster, and weight roles.202. Separate estimation choices from test-statistic and standard-error21 corrections; similarly named robust estimators do not behave identically.223. Check whether a parameter is fixed, group-constrained, or freely estimated23 before selecting a modification-index or score-test workflow.244. Preserve explicit parser, optimizer, and weighting choices when migrating25 compatibility-sensitive code.265. Open the topic reference that matches the task and retain exact option,27 operator, and parameter-table names.2829## Reference index3031| Reference | Topics |32| --- | --- |33| [model-syntax-and-estimation.md](references/model-syntax-and-estimation.md) | API and parser migration, categorical and robust estimation, instruments, composites, correlations, tuning lists, ESEM targets, and optimization |34| [groups-multilevel-and-weights.md](references/groups-multilevel-and-weights.md) | Multigroup modifiers and equality constraints, sampling weights, two-level least squares, random slopes, missing-data optimization, and level-specific fit |35| [inference-effects-and-diagnostics.md](references/inference-effects-and-diagnostics.md) | Missing-data auxiliaries, residuals, effects, structured-after-measurement inference, corrected tests, fit indices, prediction, modification diagnostics, and parameter inspection |3637## Quick reference: compatibility-sensitive changes3839### Argument and parser migration4041- Prefer `snake_case` for user-facing formal arguments. Dotted argument names42 remain accepted but are deprecated.43- Option names accept snake case or capital letters.44- The `open` syntax parser is now the default. Code that depended on the45 previous parser should choose or test parser behavior explicitly.46- The minimum R version is 3.4, and installing lavaan does not require47 compilation.4849```r50fit <- cfa(model, data = dat, sampling_weights = "weight")51```5253### Replaced tuning interfaces5455- `estimator`, `rotation`, and `bootstrap` may each be a list; use these in56 place of their separate `*.args` arguments.57- `optim_method = "gn"` now means Levenberg-Marquardt damped Fisher scoring,58 and its controls belong in `gn_args`.59- Composite models using `<~` have an analytic gradient. Remove the obsolete60 `optim_gradient = "numerical"` workaround.61- For ESEM, assign a named list of target matrices to62 `rotation_args$target` to provide one target per EFA block.6364### Fit-index naming6566- `fitMeasures()` reports the Maydeu-Olivares et al. GFI under the usual GFI67 name.68- Request `gfi_lisrel` or `agfi_lisrel` when downstream code intends the69 previously named GFI or AGFI statistics.7071## Quick reference: categorical and robust estimation7273### Categorical endogenous variables7475- lavaan supports binary and ordinal endogenous variables, not nominal ones.76- Pass selected variables with `ordered = c(...)`, or use `ordered = TRUE`77 for all endogenous variables.78- This automatically selects WLSMV: parameter estimation uses DWLS, while79 robust standard errors and the mean-and-variance-adjusted test use the full80 weight matrix.81- ULSMV and PML are alternatives. FIML is not supported for this categorical82 workflow.8384```r85fit <- cfa(model, data = dat, ordered = c("item1", "item2"))86```8788### Robust continuous-data variants8990- `MLM` uses a Satorra-Bentler test, `MLMVS` a Satterthwaite91 mean-and-variance adjustment, and `MLMV` a scale-shifted adjustment. These92 three require complete data.93- `MLF` combines first-derivative standard errors with a conventional test.94- `MLR` combines Huber-White standard errors with an asymptotic Yuan-Bentler95 test. Both `MLF` and `MLR` support complete or incomplete data.96- Less-common choices include distributionally weighted least squares97 (`DLS`) and pairwise maximum likelihood (`PML`).98- Robust DWLS and ULS variants estimate parameters with the diagonal weight99 matrix but use the full matrix for standard-error and test corrections.100101```r102fit <- cfa(model, data = dat, estimator = "MLR", missing = "ML")103```104105## Quick reference: syntax and structural choices106107### External instruments108109Use `|~` to declare external instruments and `estimator = "IV"` to select110MIIV-2SLS.111112```r113model <- '114 y ~ x115 y |~ z1 + z2116'117fit <- sem(model, data = dat, estimator = "IV")118```119120The IV implementation handles multiple groups, categorical data, simple121equality constraints, two-stage missing data, user-specified instruments,122and Sargan/Hansen overidentification tests.123124### Model composition and covariance structure125126- Pass a character vector directly as `model` to combine reusable or127 conditional syntax fragments.128- A character vector supplied to `correlation` requests a partial-correlation129 structure and can be combined with `fixed_x = TRUE`.130- `auto_cov_x = TRUE` freely estimates covariances between latent and observed131 exogenous variables; its default is `FALSE`.132- Composites support a robust mean structure, higher-order factors,133 multilevel models, and the `composites_cov` option.134- Reduced-bias M-estimation is available as an initial framework for reducing135 finite-sample bias.136137## Quick reference: groups, levels, and weights138139### Multigroup constraints140141- In multigroup syntax, `c(...)` supplies one value or label per group.142- Repeat a label to impose equality. Use `NA` at a group position to leave143 that group's parameter free while another group's value is fixed.144- `group_equal` applies supported classes of equality constraints in bulk;145 `group_partial` names exceptions in model syntax.146- `modindices()` only considers parameters fixed to zero. Use147 `lavTestScore()` to assess release of equality constraints.148149```r150fit <- cfa(151 model, data = dat, group = "school",152 group_equal = c("loadings", "intercepts"),153 group_partial = c("visual=~x2", "x7~1")154)155```156157### Two-level models158159- Two-level models can use DWLS and WLS, including WLSMV for categorical160 data; handle exogenous covariates with `fixed_x` and `conditional_x`.161- `rv()` adds random slopes to continuous two-level models. Supported paths162 include ML through `nlminb` or EM, MLR standard errors, empirical-Bayes163 predictions, and complete data or `missing = "ml"`.164- With ML missing-data handling, EM is the default two-level optimizer. It165 supports SQUAREM or quasi-Newton acceleration and analytic Louis observed166 information.167- Summaries can show level-specific fit based on partially saturated models.168 Request a level through `fitMeasures(fit, level = ...)` and control the169 behavior with `fit_by_level`.170171### Sampling weights172173- Use `sampling_weights_type` to distinguish design weights from frequency174 weights.175- Weights are normalized within group by default.176- Least-squares estimators use a properly weighted Gamma/NACOV matrix.177178## Quick reference: missing data and inference179180### Auxiliary and conditional variables181182- Supply missing-data auxiliary variables through `aux`.183- For continuous single-level models, FIML, two-stage, and robust-two-stage184 missing-data handling support `conditional_x = TRUE`, including standard185 errors and the corresponding Gamma/NACOV matrix.186187### Effects and test statistics188189- `lavEffects()` computes total, indirect, and direct effects with190 delta-method, Monte Carlo, or bootstrap standard errors.191- For parameters defined with `:=`, use `se_def = "mc"` for Monte Carlo192 standard errors and confidence intervals; `se_delta_second_order` enables193 the second-order delta option.194- Foldnes-Moss-Gronneberg statistics are available. Select the Hayakawa195 variants with `test = "mean.var.adjusted.corrected"` or196 `test = "scaled.shifted.corrected"`.197- With a robust estimator, `lavTestScore()` and `lavTestWald()` report scaled,198 adjusted, and robust statistics.199200### Residuals, prediction, and inspection201202- `lavResiduals(output = "text")` can display largest-residual tables and203 supplies elementwise residual standard errors and z-tests. It also supports204 `conditional_x`, multilevel models, and a supplied saturated model via `h1`.205- `lavPredict()` can return standard errors for categorical factor scores and206 accepts `newdata` for two-level models.207- The `mdist` casewise Mahalanobis-distance diagnostics in `lavPredict()` and208 `lavInspect()` support categorical and ordered data.209- With no `what`, `lavInspect()` returns model matrices whose nonzero integers210 identify free parameters. Use `what = "start"` for starting-value matrices211 and `what = "list"` for the full parameter table returned by212 `parTable(fit)`.213214Use the references for complete option sets, supported combinations, and215diagnostic distinctions before editing production analyses.