10  Fit measures, residuals, and other diagnostics

10.1 Why model fit matters

Once a structural equation model has been estimated, the main question for the user is rarely what the parameter estimates are, but whether the model can be trusted at all. Parameter estimates, standard errors, confidence intervals, and Wald tests are all conditional on the chosen model: they describe relationships inside the model, not the extent to which the model itself is consistent with the data. A model can be badly misspecified and still produce parameter estimates with small standard errors and tight confidence intervals. For this reason, evaluating model fit is a separate step in the analysis, and it is one that should not be skipped.

No single diagnostic answers this question. In practice, several complementary diagnostics can be used:

  1. Global fit measures summarize, in a single number, the overall discrepancy between the sample-based and the model-implied summary statistics. The chi-square test statistic is the prototype, but many descriptive indices (CFI, TLI, RMSEA, SRMR, and others) are typically reported alongside it. They give a quick overview of how well the model reproduces the sample summary statistics, but they give little information about where the model fails.

  2. Residual analysis compares each sample-based summary statistic with its model-implied counterpart, element by element: every (co)variance, mean, threshold (for categorical data), and regression slope (when conditional_x = TRUE). It is the natural way to localize the source of misfit.

  3. Casewise outlier diagnostics look at the contribution of individual observations to the discrepancy function. A small number of unusual cases can sometimes be responsible for a substantial part of the apparent misfit.

  4. Modification indices approach the problem from the opposite direction: they suggest, for each currently-fixed parameter, by how much the model chi-square would decrease if that parameter were freed. They do not repair a model, but they indicate where additional structure might be warranted.

This chapter discusses each of these diagnostics in turn. Throughout, the running example is the Holzinger–Swineford three-factor model, which we already encountered in Section 8.5.2:

model <- '
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
'
fit <- cfa(model, data = HolzingerSwineford1939)

10.2 Fit measures

A fit measure (or fit index) is a scalar summary of the discrepancy between the model-implied and the sample-based summary statistics. The chi-square test statistic, derived in Section 8.5.2, is the prototypical fit measure: under the null hypothesis that the model holds in the population, it follows a chi-square distribution with \mathrm{df} = P^{\star} - T degrees of freedom. A non-significant chi-square value is then interpreted as evidence that the model is consistent with the data. In practice, however, the chi-square test rejects the null hypothesis for even trivially-misspecified models when the sample size is large, and fails to reject it for severely-misspecified models when the sample size is small. This well-known sensitivity to N has motivated the development of descriptive fit indices that try to summarize the magnitude of misfit in a way that is less dependent on sample size.

Dozens of such indices have been proposed since the early 1980s. They differ in their reference distribution (chi-square, noncentral chi-square, none), in whether they reward or penalize parsimony, in the metric on which they are defined (probability, residual, noncentrality), and in whether they are absolute (a single model is compared to its saturated counterpart) or incremental (a single model is compared to a more restricted baseline model). lavaan implements all of the indices that have entered routine use in applied work; the complete list, with the exact formulas implemented in the source code, is the topic of this and the following sections. For more general discussions of fit measures and their behavior, see Hoyle (2012) (chapter 13 in particular) and Kenny (2020).

10.2.1 The baseline model

A large family of fit indices, including the CFI, TLI/NNFI, NFI, RFI, IFI, RNI, and PNFI, compares the discrepancy of the user-specified model to the discrepancy of a much more restrictive baseline model. An incremental index expresses how much of the misfit of the baseline model is removed by the user’s model, and its value therefore depends as much on the baseline as on the model under study. Choosing the baseline is a modeling decision in its own right, and the appropriate choice depends on the context. Widaman and Thompson (2003) spell out two requirements. The baseline model should be nested within the user’s model, so that the user’s model can be obtained from the baseline by freeing parameters; otherwise the difference between the two chi-square statistics does not correspond to a well-defined set of restrictions, and the index loses its interpretation as a proportion of misfit that is accounted for. And the baseline should be a sensible worst case for the setting at hand: a model that constrains everything the substantive question is about, but retains whatever no competing model would question.

By default, and following a tradition that goes back to Bentler and Bonett (1980), lavaan uses the so-called independence model as the baseline. For a single group of continuous observed variables, this model declares that all observed variables are mutually uncorrelated. The parameters that remain free are the P observed variances and (when a mean structure is included) the P observed intercepts. There are P(P-1)/2 off-diagonal elements of \boldsymbol{\Sigma}, all of which are constrained to zero, so the independence model has

\mathrm{df}_{B} = \frac{P(P-1)}{2} \tag{10.1}

degrees of freedom in the covariance-only case, and \mathrm{df}_{B} = P(P+1)/2 when a mean structure is included (the P intercepts now also count as fitted moments). When exogenous covariates are present and conditional_x = TRUE, those covariates are treated as fixed (just as in the user’s model), and only the residual covariance matrix of the endogenous variables is constrained to be diagonal. For categorical observed variables, the independence model is structurally similar but adapted to the polychoric/polyserial setting. The latent-response variables \mathbf{y}^{\star} are declared to be mutually uncorrelated, and the thresholds are estimated freely. Since the latent metric of an ordinal variable is not identified, a scale must be imposed: under the (default) Delta parameterization the total variance of each \mathbf{y}^{\star} is fixed at one, under the Theta parameterization its residual variance is. In the independence model there are no common factors, so the residual variance is the total variance, and both parameterizations lead to the same baseline, with every residual variance and every scaling factor fixed at one.

For most applied work (factor models, path models, and their combinations, in one or several groups, with or without a mean structure) the independence model meets both requirements. Fixing all factor loadings, regression coefficients and covariances to zero in the user’s model reproduces it, and no competing model would claim that the observed variables are unrelated. But the two requirements can fail, and when they do, the default is not the right choice. If the user’s model constrains the intercepts to be equal across groups (as in a test of scalar invariance), the independence model, which has a free intercept for every variable in every group, is no longer nested within it. In a latent growth curve model, the observed means follow from two factor means (intercept and slope), while the independence model has a free mean for every occasion; here too, the default is not nested, and it is also ill-suited to the substantive question, since the natural reference point for a growth model is the hypothesis of no change over time. Widaman and Thompson discuss these and other cases, and the literature on growth modeling has settled on a baseline with equal means across occasions, free variances and zero covariances.

This is why the choice is left to the user. The baseline_model argument of fitMeasures() (and of summary()) accepts any fitted lavaan object, and all baseline-dependent fit indices are then computed from the test statistics of that object instead of the default. lavaan checks that the supplied model was fitted with the same estimator and the same test statistic(s) as the user’s model, and refits it on the user’s data with the user’s options if not; it does not verify nesting, which remains the responsibility of the user. For the growth curve model, the equal-means baseline can be written in plain model syntax:

growth_model <- ' i =~ 1*t1 + 1*t2 + 1*t3 + 1*t4
           s =~ 0*t1 + 1*t2 + 2*t3 + 3*t4 '
fit_growth <- growth(growth_model, data = Demo.growth)

growth_baseline <- ' t1 ~ a*1; t2 ~ a*1; t3 ~ a*1; t4 ~ a*1 '
fit_growth_b <- sem(growth_baseline, data = Demo.growth, meanstructure = TRUE)

fm <- c("baseline_chisq", "baseline_df", "cfi", "tli")
fitMeasures(fit_growth, fm)
baseline.chisq    baseline.df            cfi            tli 
      1780.035          6.000          0.998          0.998 
fitMeasures(fit_growth, fm, baseline_model = fit_growth_b)
baseline.chisq    baseline.df            cfi            tli 
      2090.754          9.000          0.999          0.997 

The custom baseline has three more degrees of freedom (the four means are replaced by one), and a correspondingly larger chi-square statistic. With these data the user’s model fits so well that the indices hardly change, but that is a property of the example, not of the procedure: with a poorly fitting user model, the two baselines can lead to different conclusions.

The default baseline model is generated and fitted automatically, using the same estimator and the same options as the user’s model, with one exception: standard errors are skipped (se = "none"), because only the test statistic of the baseline model is ever used. By default, this is done immediately after the user’s model has been fitted; the baseline = FALSE option can be used to suppress it. The chi-square test statistic of the baseline model and its degrees of freedom are computed once and cached with the fitted object; the public route to them is fitMeasures():

fitMeasures(fit, c("baseline_chisq", "baseline_df", "baseline_pvalue"))
 baseline.chisq     baseline.df baseline.pvalue 
        918.852          36.000           0.000 

In what follows, we denote the chi-square test statistic of the user’s model by X^2 (with \mathrm{df} degrees of freedom), and the chi-square test statistic of the baseline model by X^2_{B} (with \mathrm{df}_{B} degrees of freedom). Unless stated otherwise, the formulas apply to whichever baseline is in use.

10.2.2 A taxonomy of fit measures

Table 10.1 lists the fit measures that lavaan can return through the fitMeasures() function, organized by family. The names in the second column are the strings that can be passed as the fit_measures = argument; the third column lists the bibliographic origin of the index; the last column indicates the section where the formula is given. Requesting a name that is not in the catalog (a typo, say) produces a warning, and the name is dropped from the output. (A valid name whose value is not available for the fitted model still returns NA.) When all (default) fit measures are requested, the returned vector carries two attributes that record which test statistics the measures are based on: standard.test (for example "standard" or "browne.residual.nt.model") and, when a scaled test was used, scaled.test (for example "satorra.bentler"). They are meant for packages that build on lavaan; the print method does not show them, and an explicit subset such as fitMeasures(fit, "cfi") is a plain named vector.

Table 10.1: Fit measures available in lavaan, grouped by family.
Family Names in lavaan Origin Section
Chi-square test chisq, df, pvalue, chisq_scaled, df_scaled, pvalue_scaled, chisq_scaling_factor, baseline_chisq, baseline_df, baseline_pvalue (with _scaled variants) see Section 8.5.2 Section 8.5
Baseline-comparison (incremental) cfi, tli, nnfi, rni, nfi, rfi, ifi, pnfi (with _scaled and _robust variants) Bentler (1990); Tucker and Lewis (1973); Bentler and Bonett (1980); Bollen (1986, 1989); McDonald and Marsh (1990); James et al. (1982) Section 10.3
Approximation (noncentrality-based) rmsea, rmsea_ci_lower, rmsea_ci_upper, rmsea_pvalue, rmsea_notclose_pvalue (with _scaled and _robust variants); mfi Steiger and Lind (1980); Browne and Cudeck (1993); McDonald (1989) Section 10.4, Section 10.6
Residual-based srmr, srmr_bentler, srmr_bentler_nomean, srmr_mplus, srmr_mplus_nomean, crmr, crmr_nomean, rmr, rmr_nomean, srmr_within, srmr_between, srmr_within_mplus, srmr_between_mplus; wrmr Jöreskog and Sörbom (1981); Bentler and Bonett (1980); Bollen (1989); Asparouhov and Muthén (2018) Section 10.5
Goodness-of-fit gfi, gfi_ci_lower, gfi_ci_upper (with _robust variants); gfi_lrt, gfi_rls; gfi_lisrel, agfi_lisrel, pgfi Maydeu-Olivares et al. (2024); Jöreskog and Sörbom (1981); Tanaka and Huba (1985); Mulaik et al. (1989) Section 10.6
Information criteria logl, unrestricted_logl, aic, bic, bic2 (a.k.a. SABIC), ntotal, npar; scaling_factor_h0, scaling_factor_h1 (Yuan–Bentler test only) Akaike (1974); Schwarz (1978); Sclove (1987) Section 10.6
Other cn_05, cn_01 (Hoelter critical N); ecvi; fmin (the minimized discrepancy function value) Hoelter (1983); Browne and Cudeck (1989) Section 10.6

The returned vector uses the dotted form of these names (cfi.scaled, rmsea.robust); the table shows the snake_case spelling used when requesting them. The names ending in .scaled are computed when a scaled chi-square test statistic (Satorra–Bentler, Yuan–Bentler, mean-and-variance adjusted, or scaled-shifted; see Section 8.5.3) is available; they are obtained by substituting the scaled statistic for the standard one in the formulas below. The names ending in .robust are computed when one of the following three settings applies:

  1. the user has requested a scaled test statistic (continuous data, nonnormal),
  2. the data are categorical and a least-squares estimator (DWLS, ULS or WLS) is used with a scaled test statistic, as in WLSMV, WLSM or ULSMV, or
  3. the data are continuous, but missing, and full-information maximum likelihood (missing = "ml" or missing = "ml.x") is used.

In each of these three cases, both the standard and the scaled chi-square statistic deviate from their target chi-square distribution in a way that distorts the descriptive fit indices that depend on them. The .robust variants apply a noncentrality reformulation due to Brosseau-Liard and Savalei (2014) (continuous nonnormal), Savalei (2018) (mean-and-variance corrected), Savalei (2021) (categorical), and Zhang and Savalei (2022) (FIML missing data). The specific formulas are given in Section 10.3.1 and Section 10.4 below.

A small notational convention applies to all fit measures below. The sample size N is the one used in the chi-square multiplier of Equation 8.38: for ML estimation with the default likelihood = "normal" setting it is N_{\mathrm{total}} (the value returned by lavInspect(object, "ntotal")), whereas for ML estimation with likelihood = "wishart", and for GLS, WLS, DWLS, or ULS estimation, it is N_{\mathrm{total}} - G.

10.3 Incremental fit indices

Incremental (or baseline-comparison) fit indices express the fit of the target model relative to the baseline model of Section 10.2.1.

10.3.1 CFI and TLI

The Comparative Fit Index [CFI; Bentler (1990)] and the Tucker–Lewis Index [TLI, also known as the Bentler–Bonett Non-Normed Fit Index, NNFI; Tucker and Lewis (1973)] are by far the most widely-reported baseline-comparison indices. Both are based on the noncentrality reformulation of the chi-square statistic: under a misspecified model, X^2 is approximately noncentrally chi-square distributed with noncentrality parameter \lambda \ge 0, and a sample-based estimate of \lambda is given by \max(X^2 - \mathrm{df}, 0).

The CFI is then defined as

\widehat{\mathrm{CFI}} = 1 \;-\; \frac{\max(X^2 - \mathrm{df},\ 0)} {\max(X^2 - \mathrm{df},\ X^2_{B} - \mathrm{df}_{B},\ 0)}. \tag{10.2}

The two max(., 0) terms ensure that \widehat{\mathrm{CFI}} lies in [0, 1], with values close to 1 indicating good fit. When both numerator and denominator are zero, which happens when neither model has any residual misfit, the CFI is set to 1 by convention. When \mathrm{df}=0 (the user’s model is saturated), \widehat{\mathrm{CFI}} = 1 as well.

The TLI replaces the noncentrality with a per-degree-of-freedom version, which gives a complexity penalty:

\widehat{\mathrm{TLI}} = 1 \;-\; \frac{(X^2 - \mathrm{df})\, \mathrm{df}_{B}} {(X^2_{B} - \mathrm{df}_{B})\, \mathrm{df}}. \tag{10.3}

Unlike the CFI, the TLI is not truncated, and can take values outside [0, 1]. The implementation in lavaan returns the formula in Equation 10.3 literally; this is algebraically equivalent to the more familiar \widehat{\mathrm{TLI}} = (X^2_B/\mathrm{df}_B - X^2/\mathrm{df}) / (X^2_B/\mathrm{df}_B - 1), but the noncentrality form is what the current implementation computes. When \mathrm{df}=0, \widehat{\mathrm{TLI}} is set to 1.

The Relative Noncentrality Index [RNI; McDonald and Marsh (1990)] is identical to the CFI but without the truncation:

\widehat{\mathrm{RNI}} = 1 \;-\; \frac{X^2 - \mathrm{df}} {X^2_{B} - \mathrm{df}_{B}}. \tag{10.4}

It can therefore exceed 1 (when X^2 < \mathrm{df}) or go below 0 (when the user’s model fits worse than the baseline). lavaan also returns this index by request, but it is rarely reported on its own.

10.3.2 Scaled CFI and TLI

When a scaled chi-square test statistic is available (for example, test = "satorra.bentler", test = "yuan.bentler", or test = "scaled.shifted"), the scaled CFI and TLI (cfi.scaled, tli.scaled) are obtained by substituting the scaled values into Equation 10.2–Equation 10.4:

\widehat{\mathrm{CFI}}_{\mathrm{scaled}} = 1 \;-\; \frac{\max(X^2_{\mathrm{scaled}} - \mathrm{df}_{\mathrm{scaled}},\ 0)} {\max(X^2_{\mathrm{scaled}} - \mathrm{df}_{\mathrm{scaled}}, \ X^2_{B,\mathrm{scaled}} - \mathrm{df}_{B,\mathrm{scaled}}, \ 0)}. \tag{10.5}

For Satorra–Bentler and Yuan–Bentler, \mathrm{df}_{\mathrm{scaled}} = \mathrm{df}; for the mean-and-variance adjusted test (mean.var.adjusted, as in MLMVS), \mathrm{df}_{\mathrm{scaled}} is the Satterthwaite value [\mathrm{tr}(\mathbf{U}\boldsymbol{\Gamma})]^{2} / \mathrm{tr}[(\mathbf{U}\boldsymbol{\Gamma})^{2}], with \mathbf{U}\boldsymbol{\Gamma} as in Equation 8.42; for the scaled-shifted test, \mathrm{df}_{\mathrm{scaled}} = \mathrm{df} but the scaled statistic itself has been shifted to match both the first and the second moment of the reference chi-square distribution.

It is well documented that the scaled CFI and TLI tend to over-estimate the true population values when the data are nonnormal (Brosseau-Liard et al., 2012; Brosseau-Liard & Savalei, 2014). The reason is that the scaling correction \hat{c} is applied identically to the user’s model and to the baseline model, but the baseline model is so badly misspecified that the scaling correction it receives is not informative.

10.3.3 Robust CFI and TLI

The robust CFI and TLI (cfi.robust, tli.robust) implement the noncentrality reformulation proposed by Brosseau-Liard and Savalei (2014), which applies the scaling correction only to the noncentrality estimate:

\widehat{\mathrm{CFI}}_{\mathrm{robust}} = 1 \;-\; \frac{\max(X^2 - \hat{c}\,\mathrm{df},\ 0)} {\max(X^2 - \hat{c}\,\mathrm{df}, \ X^2_{B} - \hat{c}_{B}\,\mathrm{df}_{B}, \ 0)}, \tag{10.6}

\widehat{\mathrm{TLI}}_{\mathrm{robust}} = 1 \;-\; \frac{(X^2 - \hat{c}\,\mathrm{df})\, \mathrm{df}_{B}} {(X^2_{B} - \hat{c}_{B}\,\mathrm{df}_{B})\, \mathrm{df}}. \tag{10.7}

In the absence of any scaling correction, \hat{c} = \hat{c}_{B} = 1 and both formulas reduce to Equation 10.2 and Equation 10.3. When a scaling correction is present, the value of \hat{c} depends on the source of the correction:

  • For the Satorra–Bentler and Yuan–Bentler tests, \hat{c} equals the average scaling correction returned by the test. For the corresponding baseline-model test, \hat{c}_{B} is the analogous scaling correction of the baseline model.

  • For the scaled-shifted test (scaled.shifted, as in MLMV and WLSMV), the test has two scaling parameters a and b, and lavaan uses \hat{c} = a\,(\mathrm{df} - b)/\mathrm{df} (Savalei, 2018, eq. 9), with the analogous \hat{c}_{B} for the baseline. No robust variants are computed for the mean-and-variance adjusted test (mean.var.adjusted).

  • For categorical data fitted with DWLS (estimator = "DWLS", "WLSMV", etc.), no scaling correction is directly available from the test; instead, lavaan evaluates the normal-theory ML discrepancy on the polychoric correlation matrix at the DWLS estimates (the catML estimator, without re-estimation), and uses the resulting X^2_{\mathrm{catML}} (Savalei, 2021) in place of X^2 in the formula of Equation 10.6. This route is not available, and the robust variants are NA, when ordinal and continuous endogenous variables are mixed, when conditional_x = TRUE, or for multilevel models. The scaling correction \hat{c}_{3} is then derived from a trace formula involving the polychoric ACOV matrix \boldsymbol{\Gamma}, the DWLS weight matrix, the normal-theory ML weight matrix, and the model Jacobian \boldsymbol{\Delta}. This construction requires the input polychoric/tetrachoric correlation matrices to be positive definite; when they are not (which is not uncommon in small samples), the robust values are reported as NA by default. The cat_nonpd option of fitMeasures() controls this behavior: "na" (the current default), "refit" (smooth the input matrix towards positive definiteness and re-estimate the model parameters with catML), or "smooth" (smooth the input matrix but keep the original DWLS estimates; this was the behavior of earlier versions). In addition, the trace-based correction for the baseline model is only valid for the default independence model: when a user-supplied baseline model is used (Section 10.2.1), the robust CFI and TLI are returned as NA. Finally, the catML discrepancy measures the fit of the model to the polychoric correlations only, where the thresholds are assumed to be free and unrestricted. Restrictions on the thresholds (thresholds that are equal across groups in a measurement invariance analysis, equal across items, or fixed) add degrees of freedom, but the corresponding misfit is not part of this discrepancy. In that case, and also when the scaling factors or the residual variances of the ordered indicators are free parameters, all the robust fit measures are reported as NA, with a warning; the scaled versions remain available.

  • For continuous data with FIML missing-data treatment, lavaan evaluates the complete-data test statistics of the user’s model and of the baseline model, at their FIML estimates, against the EM estimates of the saturated moments, and uses these statistics together with a scaling correction \hat{c}_{3} derived from the formulas of Zhang and Savalei (2022). If a user-specified \mathsf{H}_1 model is supplied (the h1_model argument of fitMeasures(), or an \mathsf{H}_1 model stored under h1.model in the object’s external list; see Section 11.2), that model is refitted to the same EM statistics, and the complete-data statistics, degrees of freedom, and correction traces are differenced between the two models, as for the Satorra–Bentler difference test; the robust CFI, TLI, RMSEA, and GFI then measure the fit relative to the \mathsf{H}_1 model.

The robust CFI and TLI are not the same as the scaled CFI and TLI: the scaled versions divide both the numerator and the denominator of the index by \hat{c}, which approximately cancels out, whereas the robust versions keep the chi-square value in its original (unscaled) metric and only subtract the corrected reference value \hat{c}\,\mathrm{df}. The robust versions are recommended whenever the data are nonnormal, categorical, or incomplete.

For the running example, with cfa() defaults (and assuming continuous normal data), the standard CFI/TLI are reported:

fitMeasures(fit, c("cfi", "tli"))
  cfi   tli 
0.931 0.896 

Refitting the same model with the Satorra–Bentler correction produces both the scaled and the robust variants:

fit_mlm <- cfa(model, data = HolzingerSwineford1939, estimator = "MLM")
fitMeasures(fit_mlm,
            c("cfi", "cfi_scaled", "cfi_robust",
              "tli", "tli_scaled", "tli_robust"))
       cfi cfi.scaled cfi.robust        tli tli.scaled tli.robust 
     0.931      0.925      0.932      0.896      0.887      0.897 

10.3.4 Other incremental fit indices

Five additional baseline-comparison indices are available. Their formulas are summarized in Table 10.2.

Table 10.2: Other incremental fit indices implemented in lavaan. All of them have .scaled variants; only the RNI (being the untruncated CFI) also has a .robust variant (rni.robust).
Index lavaan name Formula
Bentler–Bonett Normed Fit Index nfi \widehat{\mathrm{NFI}} = (X^2_{B} - X^2)/X^2_{B}
Bollen’s Relative Fit Index rfi \widehat{\mathrm{RFI}} = \dfrac{X^2_{B}/\mathrm{df}_{B} - X^2/\mathrm{df}}{X^2_{B}/\mathrm{df}_{B}}
Bollen’s Incremental Fit Index ifi \widehat{\mathrm{IFI}} = (X^2_{B} - X^2) / (X^2_{B} - \mathrm{df})
Parsimony Normed Fit Index pnfi \widehat{\mathrm{PNFI}} = (\mathrm{df}/\mathrm{df}_{B}) \cdot \widehat{\mathrm{NFI}}
Relative Noncentrality Index rni Equation 10.4

The NFI (Bentler & Bonett, 1980) suffers from a well-known downward bias in small samples. The RFI (Bollen, 1986) adds a per-degree-of-freedom adjustment to NFI that mimics the TLI; the IFI (Bollen, 1989) is a noncentrality-based modification that is less sample-size dependent than the NFI. The PNFI (James et al., 1982) multiplies the NFI by the parsimony ratio \mathrm{df}/\mathrm{df}_{B}, which rewards more constrained models. None of the five is a routine reporting requirement, but all of them are listed in the lavaan output when the user requests fit_measures = "all".

10.4 RMSEA

The Root Mean Square Error of Approximation [RMSEA; Steiger and Lind (1980); Browne and Cudeck (1993)] is the standard badness-of-fit index for SEM. It is based on the population discrepancy function value F_0 = \max(F - F_{\mathrm{population}}, 0), which can be estimated by \hat{F}_0 = \max((X^2 - \mathrm{df})/N, 0). The RMSEA re-expresses this as a per-degree-of-freedom value and takes a square root:

\widehat{\mathrm{RMSEA}} = \sqrt{\max \Bigl(\frac{X^2 - \mathrm{df}} {N\,\mathrm{df}},\ 0\Bigr)} \cdot \sqrt{G}, \tag{10.8}

where the multiplicative correction \sqrt{G} adjusts for multiple groups (Dudgeon, 2004; Steiger, 1998). The RMSEA equals zero when the model is perfect (or saturated, \mathrm{df}=0), and grows without bound as misfit increases. Values close to 0.05 are conventionally described as “good fit”; values in excess of 0.10 indicate that the model fits poorly (Browne & Cudeck, 1993).

10.4.1 Confidence interval

An important advantage of the RMSEA is that an asymptotic confidence interval is available, derived from the noncentral chi-square distribution (Browne & Cudeck, 1993). Letting F_{\chi^2_{\mathrm{df}}(\lambda)}(\cdot) denote the cumulative distribution function of the noncentral chi-square random variable with \mathrm{df} degrees of freedom and noncentrality parameter \lambda, the lower and upper bounds of a (1-\alpha) confidence interval for the noncentrality \lambda are obtained by solving

F_{\chi^2_{\mathrm{df}}(\hat{\lambda}_{L})}(X^2) = 1 - \alpha/2, \qquad F_{\chi^2_{\mathrm{df}}(\hat{\lambda}_{U})}(X^2) = \alpha/2. \tag{10.9}

If the value of X^2 is too small to admit a positive solution for \hat{\lambda}_{L} or \hat{\lambda}_{U}, the corresponding bound is set to zero. The bounds for the RMSEA are then

\widehat{\mathrm{RMSEA}}_{L} = \sqrt{\frac{\hat{\lambda}_{L}}{N\,\mathrm{df}}} \cdot \sqrt{G}, \qquad \widehat{\mathrm{RMSEA}}_{U} = \sqrt{\frac{\hat{\lambda}_{U}}{N\,\mathrm{df}}} \cdot \sqrt{G}. \tag{10.10}

The default confidence level in lavaan is 90%, which can be changed via the rmsea_ci_level option of fitMeasures(). Such fit-measure options are supplied as extra named elements of a list passed to the first (fit_measures) argument; the element named fit_measures holds the requested measures; for example, fitMeasures(fit, list(fit_measures = "rmsea_ci_upper", rmsea_ci_level = 0.95)). The older fm_args = list(...) argument is deprecated but still accepted.

10.4.2 Tests of close and not-close fit

Two one-sided hypothesis tests on the population RMSEA are available (MacCallum et al., 1996). The test of close fit has

H_{0}\!: \mathrm{RMSEA} \le \varepsilon_{0}, \qquad \varepsilon_{0} = 0.05 \text{ by default},

with p-value

p_{\mathrm{close}} = 1 - F_{\chi^2_{\mathrm{df}}(\lambda_{0})}(X^2), \qquad \lambda_{0} = \frac{N\,\mathrm{df}\,\varepsilon_{0}^{2}} {G}. \tag{10.11}

A non-significant p_{\mathrm{close}} does not reject the hypothesis of close fit. The test of not-close fit reverses the inequality,

H_{0}\!: \mathrm{RMSEA} \ge \varepsilon_{1}, \qquad \varepsilon_{1} = 0.08 \text{ by default}, \qquad p_{\mathrm{notclose}} = F_{\chi^2_{\mathrm{df}}(\lambda_{1})}(X^2), \tag{10.12}

with \lambda_{1} defined analogously to \lambda_{0}. A significant p_{\mathrm{notclose}} rejects the hypothesis of poor fit, providing positive evidence that the population RMSEA is below \varepsilon_{1}. The two thresholds can be modified via the rmsea_close_h0 and rmsea_notclose_h0 options of fitMeasures() (passed in the same way as rmsea_ci_level above).

10.4.3 Scaled and robust RMSEA

When a scaled chi-square is available, the scaled RMSEA (rmsea.scaled) substitutes scaled ingredients into Equation 10.8. Two conventions are in use here, and they differ. In the lavaan convention (the default for the satorra.bentler and mean.var.adjusted families), the unscaled statistic X^2 is referred to a (noncentral) chi-square distribution with \mathrm{tr}[\mathbf{U}\boldsymbol{\Gamma}] degrees of freedom, matching the mean of the asymptotic mixture distribution of X^2. In the Mplus convention, the scaled statistic X^2_{\mathrm{scaled}} is referred to a chi-square distribution with the scaled test’s own degrees of freedom. Because \mathrm{tr}[\mathbf{U}\boldsymbol{\Gamma}] = \hat{c} \cdot \mathrm{df}, the two conventions produce the same point estimate; but the reference distributions differ in variance, so the confidence intervals and p-values differ. For the scaled.shifted family, lavaan has always used the Mplus convention (once the statistic has been shifted, there is no meaningful trace-based route). This is why the scaled RMSEA of WLSMV and MLMV agrees with Mplus, while that of MLM, MLMVS, and MLR does not. The option rmsea_scaled_mplus = TRUE (set automatically when mimic = "Mplus") applies the Mplus convention throughout. Otherwise, the behavior is exactly analogous to the scaled CFI/TLI of Section 10.3.1.

The robust RMSEA (rmsea.robust), in contrast, applies the noncentrality reformulation (Brosseau-Liard & Savalei, 2014):

\widehat{\mathrm{RMSEA}}_{\mathrm{robust}} = \sqrt{\max \Bigl( \frac{X^2 - \hat{c}\,\mathrm{df}}{N\,\mathrm{df}},\ 0 \Bigr)} \cdot \sqrt{G}. \tag{10.13}

The scaling factor \hat{c} takes the same value as in Equation 10.6: the test-based scaling correction in the continuous nonnormal case, the a\,(\mathrm{df}-b)/\mathrm{df} value in the scaled-shifted case, the catML-based correction in the categorical case, and the EM-saturated correction in the FIML case. One detail for the categorical case: because the robust quantities are ML-based (the catML chi-square equals N_{\mathrm{total}} times the discrepancy function value), the sample size used in Equation 10.13 (and in the robust confidence interval and p-values) is N_{\mathrm{total}}, and not the N_{\mathrm{total}} - G value used by the standard and scaled RMSEA for the least-squares estimators; this also matches the output of a direct estimator = "catML" run. An algebraic identity that is sometimes useful is \widehat{\mathrm{RMSEA}}_{\mathrm{robust}} = \widehat{\mathrm{RMSEA}}_{\mathrm{scaled}} \cdot \sqrt{\hat{c}} (Brosseau-Liard & Savalei, 2014, p. 466). The robust confidence interval and robust close-fit and not-close-fit p-values are obtained by performing the noncentral chi-square inversion on the scaled statistic and then multiplying the noncentrality by \hat{c} inside the square root (for the scaled-shifted family, the multiplier is the scaling factor a rather than \hat{c}).

For the running example refitted with estimator = "MLM":

fitMeasures(fit_mlm,
            c("rmsea", "rmsea_scaled", "rmsea_robust",
              "rmsea_ci_lower_robust", "rmsea_ci_upper_robust",
              "rmsea_pvalue_robust"))
                rmsea          rmsea.scaled          rmsea.robust 
                0.092                 0.089                 0.091 
rmsea.ci.lower.robust rmsea.ci.upper.robust   rmsea.pvalue.robust 
                0.070                 0.113                 0.001 

10.5 SRMR and related indices

The Standardized Root Mean Square Residual (SRMR) is the most widely-used absolute fit index that does not depend on the chi-square statistic. It summarizes the size of the standardized residuals: the differences between the sample-based and the model-implied summary statistics ((co)variances and, when a mean structure is present, means), expressed in correlation-like units. Several variants are in use, and lavaan computes all of them; the one returned under the bare name srmr is the Bentler/EQS variant, with the mean residuals included whenever the model has a mean structure (for categorical data, the threshold residuals are never included).

10.5.1 The kernel formula

All variants share the same kernel: each is the root-mean-square of a vector of residuals, taken over a chosen index set. Let \mathbf{r} collect the relevant residuals and let p^{\star} denote the number of elements summed; then

\mathrm{rms}(\mathbf{r}) = \sqrt{\frac{\mathbf{r}^{\prime}\mathbf{r}} {p^{\star}}}. \tag{10.14}

The variants differ in the definition of \mathbf{r} and in the value of p^{\star} (whether the diagonal elements are included or not, whether the mean-structure residuals are included or not, whether residuals are standardized using sample variances, model-implied variances, or both). The per-variant choices are summarized in Table 10.3 below.

For multiple groups, every variant is computed per group and combined into a single value as a sample-size-weighted average,

\widehat{\mathrm{SRMR}} = \sum_{g=1}^{G} \frac{N_{g}}{N_{\mathrm{total}}}\, \widehat{\mathrm{SRMR}}_{g}. \tag{10.15}

10.5.2 The Bentler/EQS variant (srmr_bentler, the lavaan default)

The default is the variant proposed by Bentler in EQS, in which both sample and model-implied (co)variances are rescaled by the sample standard deviations \sqrt{S_{pp}} before the residual is taken (Bentler & Bonett, 1980; for a recent treatment see Maydeu-Olivares, 2017). For a single group, no mean structure, and observed variables indexed by p, p' \in \{1, \ldots, P\}:

\widehat{\mathrm{SRMR}}_{\mathrm{Bentler,nomean}} = \sqrt{\frac{1}{P(P+1)/2}\, \sum_{p \le p'} \biggl(\frac{S_{pp'} - \hat{\Sigma}_{pp'}} {\sqrt{S_{pp}\,S_{p'p'}}}\biggr)^{\!2}}. \tag{10.16}

The diagonal contribution is (1 - \hat{\Sigma}_{pp}/S_{pp})^2, which is nonzero whenever the model does not exactly reproduce the sample variances. When a mean structure is included (e.g., in growth()-type models or meanstructure = TRUE), P standardized mean residuals (\bar{y}_{p} - \hat{\mu}_{p})/\sqrt{S_{pp}} are added to the residual vector, and p^{\star} becomes P(P+1)/2 + P:

\widehat{\mathrm{SRMR}}_{\mathrm{Bentler}} = \sqrt{\frac{ \sum_{p \le p'}\bigl((S_{pp'}-\hat{\Sigma}_{pp'})/\sqrt{S_{pp}S_{p'p'}}\bigr)^{2} + \sum_{p}\bigl((\bar{y}_{p}-\hat{\mu}_{p})/\sqrt{S_{pp}}\bigr)^{2} }{P(P+1)/2 + P}}. \tag{10.17}

The lavaan name srmr returns Equation 10.17 when a mean structure is in the model, and Equation 10.16 otherwise. Both forms are also exposed under the explicit names srmr_bentler and srmr_bentler_nomean.

10.5.3 Bollen’s correlation residual (crmr)

Bollen’s CRMR uses true correlation residuals: the sample correlation matrix and the model-implied correlation matrix are differenced element-wise. By construction, the diagonal of this difference is zero, so only the P(P-1)/2 off-diagonal elements are summed:

\widehat{\mathrm{CRMR}}_{\mathrm{nomean}} = \sqrt{\frac{1}{P(P-1)/2}\, \sum_{p < p'} \biggl(\frac{S_{pp'}}{\sqrt{S_{pp}S_{p'p'}}} - \frac{\hat{\Sigma}_{pp'}}{\sqrt{\hat{\Sigma}_{pp}\hat{\Sigma}_{p'p'}}}\biggr)^{\!2}}. \tag{10.18}

The mean-structure version is analogous, with the same standardized mean residuals as in Equation 10.17. CRMR differs from SRMR (Bentler) in that it is zero at the diagonal by construction, whereas SRMR (Bentler) is not: this is why the two indices can differ noticeably in practice.

10.5.4 The Mplus convention (srmr_mplus)

Mplus uses a slightly different definition: the off-diagonal elements follow Bollen’s correlation residual, but the diagonal contribution is the standardized variance residual (S_{pp} - \hat{\Sigma}_{pp})/S_{pp} (Asparouhov & Muthén, 2018). With a mean structure, the standardized mean residuals use the model-implied variances in the denominator, (\bar{y}_{p} - \hat{\mu}_{p})/\sqrt{\hat{\Sigma}_{pp}}, rather than the sample variances. Putting these together, with e = P(P+1)/2 + P:

\widehat{\mathrm{SRMR}}_{\mathrm{Mplus}} = \sqrt{\frac{1}{e}\!\left[ \sum_{p < p'}\!\biggl(\!\frac{S_{pp'}}{\sqrt{S_{pp}S_{p'p'}}} - \frac{\hat{\Sigma}_{pp'}}{\sqrt{\hat{\Sigma}_{pp}\hat{\Sigma}_{p'p'}}}\biggr)^{\!2} \!+\! \sum_{p}\!\biggl(\!\frac{S_{pp}-\hat{\Sigma}_{pp}}{S_{pp}}\biggr)^{\!2} \!+\! \sum_{p}\!\biggl(\!\frac{\bar{y}_{p}-\hat{\mu}_{p}}{\sqrt{\hat{\Sigma}_{pp}}}\biggr)^{\!2} \right]}. \tag{10.19}

The _nomean version omits the third sum and uses e = P(P+1)/2 in the denominator. The default mimic = "lavaan" returns the Bentler variants; setting mimic = "Mplus" together with information = "observed" causes lavaan to use Equation 10.19 (or its nomean version) under the bare name srmr.

10.5.5 Raw residuals (rmr) and weighted residuals (wrmr)

The Root Mean Square Residual (RMR) is identical to Equation 10.17 but with the raw (unstandardized) residuals S_{pp'} - \hat{\Sigma}_{pp'} in place of the standardized residuals. It depends on the metric of the observed variables, which limits its utility unless all variables have a common scale. The Weighted Root Mean Square Residual is computed only for categorical estimators and is

\widehat{\mathrm{WRMR}} = \sqrt{\frac{X^2}{K}}, \tag{10.20}

where K is the number of (unique) sample statistics in the first group’s WLS-style sample-statistics vector.1 The WRMR is essentially a re-expression of the chi-square statistic, and is included mostly for backward compatibility with Mplus output.

10.5.6 Multilevel: srmr_within and srmr_between

For two-level models (lavaan(...) with a cluster= argument), lavaan reports separate SRMR values for the within-level and between-level covariance matrices. Each of these is a root-mean-square of the correlation residuals of Equation 10.18 at that level (the sample and model-implied covariance matrices of that level are both converted to correlations and differenced element-wise), with the P(P+1)/2 elements of the half-vectorization, diagonal included, in the denominator and P the number of variables at that level. The total srmr returned at the multilevel level is the sum (not the average) of the within- and between-level values.

Two alternative versions, srmr_within_mplus and srmr_between_mplus, follow the definition used by recent versions of Mplus (8.1 and later; older versions agree with the values above). They differ in three respects. The diagonal elements are the relative variance residuals (S_{pp}-\hat{\Sigma}_{pp})/S_{pp} of the srmr_mplus variant, instead of the zeros of a correlation residual. The mean residuals are included, divided by the standard deviations of the unrestricted model: the means of the variables that are split into a within and a between component are the total means and belong to the between level, so that only the means of the within-only variables are counted at the within level. And the elements that involve only fixed exogenous covariates, which cannot contribute any misfit, are not counted, neither in the sum nor in the number of elements. With mimic = "Mplus", these are also the values reported under the names srmr_within and srmr_between (and their sum under srmr). Level-specific versions of the chi-square-based fit measures (CFI, TLI, RMSEA, …) require auxiliary partially saturated models, and are discussed in Section 10.7.

10.5.7 Summary of the SRMR variants

Table 10.3 summarizes the eight scalar residual-based fit indices that lavaan can return (four variants, each with and without the mean-structure residuals), in the most common (single-group, single-level, continuous-data) setting.

Table 10.3: Definition of the residual-based fit indices in lavaan. Each is computed as \sqrt{(\sum r_{i}^{2})/p^{\star}} where the index set sums over the listed residual types. The plain name srmr is an alias for srmr_bentler when a mean structure is present, and for srmr_bentler_nomean otherwise (always the latter for categorical data).
lavaan name Off-diagonal Diagonal Mean p^{\star}
rmr S_{pp'}-\hat{\Sigma}_{pp'} S_{pp}-\hat{\Sigma}_{pp} \bar{y}_{p}-\hat{\mu}_{p} P(P+1)/2 + P
rmr_nomean S_{pp'}-\hat{\Sigma}_{pp'} S_{pp}-\hat{\Sigma}_{pp} none P(P+1)/2
srmr_bentler \dfrac{S_{pp'}-\hat{\Sigma}_{pp'}}{\sqrt{S_{pp}S_{p'p'}}} 1-\dfrac{\hat{\Sigma}_{pp}}{S_{pp}} \dfrac{\bar{y}_{p}-\hat{\mu}_{p}}{\sqrt{S_{pp}}} P(P+1)/2 + P
srmr_bentler_nomean \dfrac{S_{pp'}-\hat{\Sigma}_{pp'}}{\sqrt{S_{pp}S_{p'p'}}} 1-\dfrac{\hat{\Sigma}_{pp}}{S_{pp}} none P(P+1)/2
crmr \dfrac{S_{pp'}}{\sqrt{S_{pp}S_{p'p'}}} - \dfrac{\hat{\Sigma}_{pp'}}{\sqrt{\hat{\Sigma}_{pp}\hat{\Sigma}_{p'p'}}} 0 \dfrac{\bar{y}_{p}-\hat{\mu}_{p}}{\sqrt{S_{pp}}} P(P-1)/2 + P
crmr_nomean as above 0 none P(P-1)/2
srmr_mplus \dfrac{S_{pp'}}{\sqrt{S_{pp}S_{p'p'}}} - \dfrac{\hat{\Sigma}_{pp'}}{\sqrt{\hat{\Sigma}_{pp}\hat{\Sigma}_{p'p'}}} \dfrac{S_{pp}-\hat{\Sigma}_{pp}}{S_{pp}} \dfrac{\bar{y}_{p}-\hat{\mu}_{p}}{\sqrt{\hat{\Sigma}_{pp}}} P(P+1)/2 + P
srmr_mplus_nomean as above \dfrac{S_{pp}-\hat{\Sigma}_{pp}}{S_{pp}} none P(P+1)/2

For categorical observed variables, the same kernel is applied to polychoric and polyserial correlation residuals; the threshold residuals are summarized separately. The srmr_mplus and srmr_mplus_nomean values are reported as NA for categorical models: lavaan 0.7-4 does not implement the corresponding Mplus formula (the one Mplus uses since version 8.1).

For the running example:

fitMeasures(fit, c("srmr", "srmr_bentler", "crmr", "rmr"))
        srmr srmr_bentler         crmr          rmr 
       0.065        0.065        0.073        0.082 

10.6 Other fit measures

The remaining fit indices that lavaan returns are descriptive measures that are mostly carried over from earlier generations of SEM software, or that are useful for model comparison rather than for absolute model evaluation.

10.6.1 Information criteria

For ML estimation, lavaan reports the loglikelihood at the estimated parameter values \ell(\hat{\boldsymbol{\vartheta}}) (logl) and at the saturated unrestricted model \ell(\tilde{\boldsymbol{\vartheta}}) (unrestricted.logl). These loglikelihood values are used to construct three information criteria:

\mathrm{AIC} = -2\,\ell(\hat{\boldsymbol{\vartheta}}) + 2\,T, \tag{10.21}

\mathrm{BIC} = -2\,\ell(\hat{\boldsymbol{\vartheta}}) + T\, \log(N), \tag{10.22}

\mathrm{SABIC} = -2\,\ell(\hat{\boldsymbol{\vartheta}}) + T\, \log\!\left(\frac{N+ 2}{24}\right), \tag{10.23}

referred to as aic (Akaike, 1974), bic (Schwarz, 1978), and bic2 (Sclove, 1987). In all three cases, T is the number of free model parameters as returned by lavInspect(object, "npar") (after equality constraints are applied), and N is the unmodified total sample size N_{\mathrm{total}} (note that this differs from the N used in Equation 10.8). When the Yuan–Bentler scaled test is used, two additional scaling factors scaling.factor.h0 and scaling.factor.h1 are stored, but they are not currently incorporated into AIC/BIC/SABIC.

Information criteria are not on a meaningful absolute scale; they are useful only for comparing nested or non-nested models fitted on the same data. Smaller values indicate better fit. The BIC penalizes complexity more heavily than the AIC for any sample size with \log(N) > 2, i.e., for N> 7.

fitMeasures(fit, c("logl", "aic", "bic", "bic2"))
     logl       aic       bic      bic2 
-3737.745  7517.490  7595.339  7528.739 

For models with a casewise likelihood (random slopes, Section 16.13; and data-defined parameters estimated by an external backend, Section 2.9), no test statistic and no comparable unrestricted model exist, and the information criteria are all that fitMeasures() can offer: only npar, ntotal, logl, aic, bic, and bic2 are returned (plus scaling_factor_h0 for random slopes with robust standard errors); requesting any other measure is an error that names the measure.

10.6.2 Goodness-of-fit indices: GFI, AGFI, PGFI

Since version 0.7-2, the name gfi refers to the “rediscovered” goodness-of-fit index of Maydeu-Olivares et al. (2024), who re-interpret the GFI as the proportion of the total (weighted, squared) sample moments that is accounted for by the model, the SEM analogue of R^2 in regression (without an intercept), with the saturated model as the reference. For a single group, the point estimate is

\widehat{\mathrm{GFI}} = \min\!\left( \frac{N\,P} {N\,P+ 2\,(X^{2} - \hat{c}\,\mathrm{df})}, \ 1\right), \tag{10.24}

where \hat{c} = 1 for the standard version, and \hat{c} equals the robust scaling correction of Equation 10.13 for the .robust variant. Following the recommendation of Maydeu-Olivares et al. (2024), the test statistic X^{2} in Equation 10.24 is by default the reweighted least squares (RLS) statistic (test = "browne.residual.nt.model" in lavaan) rather than the likelihood-ratio statistic; both versions can be requested explicitly under the names gfi_rls (identical to gfi) and gfi_lrt. (For categorical data and for FIML estimation, no separate RLS statistic is available, and the likelihood-ratio-based statistic is used throughout.) The likelihood-ratio version gfi_lrt is a simple transformation of the RMSEA: for a single group, \widehat{\mathrm{GFI}} = P/ (P+ 2\,\mathrm{df}\, \widehat{\mathrm{RMSEA}}^{2}) (Maydeu-Olivares et al., 2024, eq. 26) (the RLS-based gfi differs slightly, since it starts from a different statistic), and a confidence interval (gfi.ci.lower, gfi.ci.upper; 90% by default, controlled by the gfi_ci_level option) is obtained from the same noncentral chi-square inversion as in Equation 10.9, with each noncentrality bound \hat{\lambda} mapped to the GFI metric as N\,P/ (N\,P+ 2\,\hat{c}\,\hat{\lambda}) (truncated at 1); note that the lower noncentrality bound yields the upper GFI bound, and vice versa. The new GFI (with its confidence interval) is part of the default fit-measure set, and is printed by summary(fit, fit_measures = TRUE).

The original LISREL-style goodness-of-fit index (Jöreskog & Sörbom, 1981; Tanaka & Huba, 1985) was available up to version 0.6 under the name gfi, and was renamed gfi_lisrel in 0.7-2. It expresses the relative discrepancy between the model and the data in the metric of the discrepancy function. Let \mathbf{s} be the vector of sample summary statistics (lavInspect(object, "wls_obs")), \boldsymbol{\sigma}(\boldsymbol{\vartheta}) the corresponding model-implied vector (lavInspect(object, "wls_est")), and \mathbf{W} the weight matrix used in the discrepancy function (lavInspect(object, "wls_v")). Then, per group,

\widehat{\mathrm{GFI}}_{g} = 1 - \frac{(\mathbf{s} - \boldsymbol{\sigma}(\boldsymbol{\vartheta}))^{\prime}\, \mathbf{W}\, (\mathbf{s} - \boldsymbol{\sigma}(\boldsymbol{\vartheta}))} {\mathbf{s}^{\prime}\,\mathbf{W}\,\mathbf{s}}. \tag{10.25}

When \mathbf{W} is diagonal (e.g., for ULS or DWLS), the matrix operations reduce to a sum of weighted squared residuals. In the multigroup case, the per-group GFIs are combined as \widehat{\mathrm{GFI}} = \sum_{g} (N_{g}/ N_{\mathrm{total}})\, \widehat{\mathrm{GFI}}_{g}.

The Adjusted GFI (agfi_lisrel; up to version 0.6: agfi) rescales the LISREL GFI to penalize complexity. With K the number of fitted moments (the length of \mathbf{s}),

\widehat{\mathrm{AGFI}} = 1 - \frac{K}{\mathrm{df}}\,(1 - \widehat{\mathrm{GFI}}). \tag{10.26}

The Parsimony GFI (pgfi, also based on the LISREL GFI) multiplies the GFI by the parsimony ratio (Mulaik et al., 1989):

\widehat{\mathrm{PGFI}} = \frac{\mathrm{df}}{K}\,\widehat{\mathrm{GFI}}. \tag{10.27}

The LISREL-style GFI, AGFI, and PGFI have gradually fallen out of use, because they tend to be sample-size dependent and are not well-behaved for misspecified models (Hu & Bentler, 1998). lavaan still reports them on request (under their _lisrel names) for single-level models fitted with any estimator that produces the ingredients of Equation 10.25: the ML, GLS and least-squares estimators, including their categorical versions, and the multi-stage estimators of Chapter 17 (IV, James–Stein, MGM). The exception is pairwise maximum-likelihood (PML) estimation, where the weight matrix is not defined; for multilevel models they are not reported. Whether the noncentrality-based reformulation of Maydeu-Olivares et al. (2024) will restore the GFI to routine reporting practice remains to be seen.

10.6.3 Hoelter’s Critical N

Hoelter (1983) proposed a simple inversion of the chi-square test: the critical sample size at significance level \alpha is the largest N^{\star} that would have produced a non-rejected chi-square test, given the observed value of X^2/N. The formula is

\widehat{\mathrm{CN}}_{\alpha} = \frac{\chi^{2}_{1-\alpha}(\mathrm{df})}{X^{2}/N} + 1, \tag{10.28}

where \chi^{2}_{1-\alpha}(\mathrm{df}) denotes the 1-\alpha quantile of the central chi-square distribution with \mathrm{df} degrees of freedom. lavaan reports the values for \alpha = 0.05 (cn_05) and \alpha = 0.01 (cn_01). Values above 200 are conventionally interpreted as evidence of acceptable fit at the chosen significance level.

10.6.4 McDonald’s Fit Index

McDonald (1989) introduced an exponential transform of the noncentrality:

\widehat{\mathrm{MFI}} = \exp\!\Bigl[-\tfrac{1}{2}\,(X^{2} - \mathrm{df})/N\Bigr]. \tag{10.29}

It maps badness-of-fit (large noncentrality) to a number between 0 and 1 (with values close to 1 indicating good fit) without truncation, and is sometimes preferred to the GFI for its more interpretable scale. There is no scaled or robust variant.

10.6.5 Expected cross-validation index

Browne and Cudeck (1989) proposed the ECVI as a single-sample estimator of the expected discrepancy between the fitted model and the population covariance matrix in a future sample of the same size:

\widehat{\mathrm{ECVI}} = \frac{X^{2}}{N} + \frac{2\,T}{N}. \tag{10.30}

It is most useful as a model-comparison criterion within the same dataset. The ECVI is not currently defined for multigroup or mean-structured models, although lavaan reports a value for both cases (with the standard multigroup chi-square in the numerator).

fitMeasures(fit, c("cn_05", "cn_01", "gfi", "gfi_ci_lower", "gfi_ci_upper",
                   "gfi_lisrel", "agfi_lisrel", "pgfi", "mfi", "ecvi"))
       cn_05        cn_01          gfi gfi.ci.lower gfi.ci.upper   gfi_lisrel 
     129.490      152.654        0.959        0.939        0.976        0.943 
 agfi_lisrel         pgfi          mfi         ecvi 
       0.894        0.503        0.903        0.423 

10.7 Level-specific fit measures for multilevel models

For a two-level model, the chi-square test statistic, and every fit measure derived from it, summarizes the misfit of both levels at once. This global summary can be misleading: the within level is typically estimated from far more information (the total number of observations) than the between level (the number of clusters), so the pooled fit measures tend to be dominated by the within part of the model. A badly misspecified between-level model can go undetected when the within-level model fits well (Ryu & West, 2009). Everything in this section presumes a two-level model with random intercepts only, the setting in which a saturated model, and hence a chi-square statistic, exists. For models with random slopes (the rv() modifier, Section 16.13), lavaan 0.7-4 provides no chi-square statistic and no fit indices, so neither the global nor the level-specific fit measures of this section apply.

The remedy proposed by Ryu and West (2009) is the partially saturated model approach. To assess the fit of, say, the within part of the model, an auxiliary model is fitted in which the within part is copied from the user’s model, while the between part is saturated. Since a saturated level cannot contribute any misfit, whatever misfit remains in this partially saturated model can be attributed to the within level alone. The same construction with the roles reversed isolates the between-level misfit. For the incremental fit indices (CFI, TLI, and the other baseline-comparison indices), a level-specific baseline model is needed as well: the independence model at the target level, again combined with a saturated model at the other level.

lavaan automates this procedure. When a multilevel model is fitted, the partially saturated models (and their level-specific baseline models) are estimated automatically, and their essentials are stored inside the fitted object (see the fit_by_level option in lavOptions(), which is currently TRUE by default for multilevel models). The fitMeasures() function then accepts a level = argument: either a level number (1 or 2), one of "within" and "between", or the level label used in the model syntax. Consider a two-level model for the Demo.twolevel dataset:

model2l <- '
  level: within
    fw =~ y1 + y2 + y3
    fw ~ x1 + x2 + x3
  level: between
    fb =~ y1 + y2 + y3
    fb ~ w1 + w2
'
fit2l <- sem(model2l, data = Demo.twolevel, cluster = "cluster")
fitMeasures(fit2l, c("chisq", "df", "pvalue", "cfi", "rmsea"))
 chisq     df pvalue    cfi  rmsea 
 8.092 10.000  0.620  1.000  0.000 

The level-specific versions are obtained as follows:

fitMeasures(fit2l, c("chisq", "df", "pvalue", "cfi", "rmsea"),
            level = "within")
Fit measures for the within level only (the other level is saturated):

 chisq     df pvalue    cfi  rmsea 
 1.352  6.000  0.969  1.000  0.000 
fitMeasures(fit2l, c("chisq", "df", "pvalue", "cfi", "rmsea"),
            level = "between")
Fit measures for the between level only (the other level is saturated):

 chisq     df pvalue    cfi  rmsea 
 6.656  4.000  0.155  0.991  0.058 

Each call reports the fit measures of the partially saturated model for that level; because each partially saturated fit carries its own level-specific baseline model, the incremental indices are automatically computed with respect to the correct baseline. The RMSEA deserves a remark: its formula involves the sample size (Section 10.4), and at the between level the independent units are the clusters. Following Ryu and West (2009), the between-level RMSEA (and its confidence interval and p-values) is therefore based on the number of clusters J, rather than the total sample size N; the within-level RMSEA is still based on N. Note that the degrees of freedom of the two partially saturated models add up to the degrees of freedom of the original model (here, 6 + 4 = 10), as they must when no constraints link the two levels; the chi-square statistics themselves decompose only approximately (here, 1.352 + 6.656 = 8.008 \approx 8.092). When a scaled test statistic is requested (e.g., estimator = "MLR"), the partially saturated fits inherit it, and the scaled and robust variants (e.g., cfi.robust, rmsea.robust) become available at each level as well. The same information is printed by summary(fit2l, fit_measures = TRUE), as a compact measures-by-levels table under the heading “Level-specific Fit Measures (other level saturated)”. The SRMR needs no auxiliary fits: the srmr_within and srmr_between values of Section 10.5 are level-specific by construction, and they are reused in the summary table.

A few restrictions apply. Level-specific fit is not defined when (equality) constraints involve parameters from different levels; in that case, no partially saturated fits are produced (silently), and an error message is given only when level-specific fit measures are requested explicitly (see Section 16.4.5). Level-specific fit is currently not available for models with random slopes, EFA blocks, categorical endogenous variables, conditional_x = TRUE, correlation structures, or free group weights. Finally, if the partially saturated fits were not stored (e.g., because the model was fitted with fit_by_level = FALSE), fitMeasures(..., level = ) re-fits them when called.

10.8 Residuals

A fit measure is a summary: it collapses the entire pattern of discrepancy between the model-implied and the sample-based summary statistics into a single number. This is convenient, but much information is lost. Two models with the same value of the SRMR can have very different residual patterns, and only the latter tells the user where, among the summary statistics, the model fails to reproduce the data. Inspecting the residuals, element by element and with their signs and magnitudes, is therefore the natural complement to inspecting the overall fit measures.

In SEM, two notions of “residual” coexist:

  1. Summary-statistic residuals compare the sample (or unrestricted-h1) summary statistics with their model-implied counterparts: \mathbf{e} = \mathbf{s}- \boldsymbol{\sigma}(\boldsymbol{\hat{\vartheta}}). They are defined in the same space as \mathbf{s} and may include residuals on (co)variances, means, thresholds, and slopes, depending on what the model contains.
  2. Casewise residuals compare each individual observation with its model-implied prediction: \hat{\mathbf{e}}_{i} = \mathbf{y}_{i} - \hat{\mathbf{y}}_{i}. They are defined in the data space and have the same dimensionality as the raw data.

The first kind is what the SEM tradition has historically focused on, and is by far the more informative for model diagnostics. The second kind is useful for case diagnostics, in the same spirit as residual plots in regression. Both are accessible in lavaan; we discuss them in turn.

10.8.1 Why standardize residuals?

The discussion below is framed in terms of (co)variance residuals, since that is the residual block that is most commonly inspected in practice; the same logic applies to mean residuals (when a mean structure is present), threshold residuals (for categorical data), and slope residuals (for conditional_x = TRUE), each of which is on its own metric and benefits from a comparable standardization.

For a continuous-data CFA or path model, the raw covariance residuals S_{pp'} - \hat{\Sigma}_{pp'} are immediately interpretable: a positive value means the model under-predicts the covariance, a negative value means it over-predicts. But raw residuals depend on the metric of the observed variables: a residual covariance of 0.05 is a small misfit if the variables are on a 0–100 scale, and a large one if they are on a 0–1 scale. When variables are measured on different scales, a single table of raw residuals is hard to read.

The standard remedy is to bring the residuals to a common, unit-free metric. Three choices, each with a different rationale, are in routine use:

  1. Rescale by sample standard deviations only. Both the sample and the model-implied (co)variance are divided by \sqrt{S_{pp}\,S_{p'p'}}, yielding a residual on a correlation-like scale. The diagonal is not zero in general: it equals 1 - \hat{\Sigma}_{pp}/S_{pp}, the proportional misfit of the variance. This is the Bentler and Bonett (1980) /EQS convention, returned by lavResiduals() under the default type = "cor_bentler" and used as the kernel of the SRMR fit index (see Section 10.5).

  2. Take a difference of correlations. The sample correlation matrix \mathbf{R} is differenced from the model-implied correlation matrix \hat{\mathbf{P}} = \text{cov2cor}(\hat{\boldsymbol{\Sigma}}). The diagonal is identically zero by construction. This is Bollen’s correlation residual (CRMR) (Bollen, 1989; Maydeu-Olivares, 2017).

  3. Divide by the asymptotic standard error of the residual itself. Each S_{pp'} - \hat{\Sigma}_{pp'} is divided by an estimate of its sampling standard deviation, yielding a quantity that is approximately standard-normal under the null hypothesis that the model is correct. This is the most directly inferential form of standardization, and is what most SEM software calls a “standardized residual”.

The first two transformations make the residuals scale-comparable but do not by themselves give a hypothesis test. The third does, but requires a non-trivial computation involving both the asymptotic covariance of \mathbf{s} and the sensitivity of \boldsymbol{\sigma}(\boldsymbol{\hat{\vartheta}}) to the fitted parameters. As Maydeu-Olivares (2017) emphasizes, the three strategies should be reported together: a global SRMR/CRMR for an overall effect size, and a table of standardized residuals (option 3) for localizing the misfit.

10.8.2 The lavResiduals() function

The function lavResiduals() is the unified entry point for residual diagnostics in lavaan. By default, it returns the residuals on the correlation-like (Bentler) scale, together with their element-wise asymptotic z-statistics and a summary table containing the SRMR, the unbiased SRMR of Maydeu-Olivares (2017), their standard errors, 90% confidence intervals, and tests of exact and close fit:

res <- lavResiduals(fit)
names(res)
[1] "type"    "cov"     "cov.z"   "summary"
res$summary
                          cov
srmr                    0.065
srmr.se                 0.006
srmr.exactfit.z         6.063
srmr.exactfit.pvalue    0.000
usrmr                   0.058
usrmr.se                0.010
usrmr.ci.lower          0.042
usrmr.ci.upper          0.074
usrmr.closefit.h0.value 0.050
usrmr.closefit.z        0.832
usrmr.closefit.pvalue   0.203

The most important argument is type, which selects the metric of the residuals and is the topic of the next section. The remaining arguments switch the individual components of the output on or off (the z-statistics, the summary table, the unbiased estimator, the confidence level and the close-fit cutoff of the summary table, the output format) and are described in Section 10.8.5. The residuals() method (Section 10.8.6) uses the same machinery with most of these components switched off.

10.8.3 The type argument

type controls how the element-by-element residuals are computed and returned. Eleven values are recognized, but several are aliases. The distinct cases are summarized in Table 10.4.

Table 10.4: Residual types returned by lavResiduals() (and by residuals(), resid()). For each type, the per-element formula is given for the covariance residuals; mean residuals (when a mean structure is present) follow analogous rules.
type = Element formula Notes
"raw" (alias "rmr") r_{pp'} = S_{pp'} - \hat{\Sigma}_{pp'} residuals on the original (co)variance scale
"cor_bentler" (alias "srmr", "cor_eqs") r_{pp'}^{B} = \dfrac{S_{pp'} - \hat{\Sigma}_{pp'}}{\sqrt{S_{pp}\,S_{p'p'}}} both sides rescaled by sample SDs; diagonal nonzero
"cor_bollen" (alias "crmr") r_{pp'}^{C} = \dfrac{S_{pp'}}{\sqrt{S_{pp}\,S_{p'p'}}} - \dfrac{\hat{\Sigma}_{pp'}}{\sqrt{\hat{\Sigma}_{pp}\,\hat{\Sigma}_{p'p'}}} residual of the correlation matrices; diagonal zero
"cor" as "cor_bentler" if mimic = "EQS", else as "cor_bollen" metric-free convenience alias
"normalized" r_{pp'}^{N} = \dfrac{S_{pp'} - \hat{\Sigma}_{pp'}}{\sqrt{[\widehat{\text{Var}}(\mathbf{s})]_{(pp'),(pp')}}} divides by asymptotic SE of \mathbf{s} alone; conservative test
"standardized" r_{pp'}^{S} = \dfrac{S_{pp'} - \hat{\Sigma}_{pp'}}{\sqrt{[\widehat{\text{Var}}(\mathbf{s}- \boldsymbol{\sigma}(\boldsymbol{\hat{\vartheta}}))]_{(pp'),(pp')}}} divides by SE that accounts for sampling of both sides
"standardized_mplus" as above, but with the projection-free Mplus variance formula computationally simpler; can return NA if the variance estimate goes negative

The two purely descriptive types, "cor_bentler" and "cor_bollen", provide the kernel for the SRMR and CRMR fit indices discussed in Section 10.5; the choice between them mirrors the choice of srmr vs crmr. The “normalized” residual divides only by the sampling standard deviation of \mathbf{s}:

\text{Var}\bigl(\mathbf{s}\bigr) \;\approx\; \boldsymbol{\Gamma}/N,

obtained from the unrestricted (\mathsf{H}_1) model’s asymptotic information. This ignores the (negative) contribution of \boldsymbol{\sigma}(\boldsymbol{\hat{\vartheta}})’s own sampling variability to \text{Var}(\mathbf{s}- \boldsymbol{\sigma}(\boldsymbol{\hat{\vartheta}})), which means that the resulting z-statistic is conservative: it under-estimates the absolute size of standardized residuals.

The “standardized” residual remedies this. The asymptotic covariance of the residual vector \mathbf{e} = \mathbf{s}- \boldsymbol{\sigma}(\boldsymbol{\hat{\vartheta}}) is computed as

\widehat{\text{Var}}(\mathbf{e}) \;=\; \mathbf{Q}\,\widehat{\text{Var}}(\mathbf{s})\,\mathbf{Q}^{\prime}, \qquad \mathbf{Q} = \mathbf{I} - \widehat{\text{Var}}(\boldsymbol{\sigma}(\boldsymbol{\hat{\vartheta}}))\, \mathbf{A}_{E}(\mathbf{s}), \tag{10.31}

where \widehat{\text{Var}}(\boldsymbol{\sigma}(\boldsymbol{\hat{\vartheta}})) = \boldsymbol{\Delta}(\hat{\boldsymbol{\vartheta}})\, [\boldsymbol{\Delta}(\hat{\boldsymbol{\vartheta}})^{\prime} \mathbf{A}_{E}(\boldsymbol{\sigma})\, \boldsymbol{\Delta}(\hat{\boldsymbol{\vartheta}})]^{-1}\, \boldsymbol{\Delta}(\hat{\boldsymbol{\vartheta}})^{\prime} is the implied moments’ delta-method covariance, \mathbf{A}_{E}(\boldsymbol{\sigma}) is the \mathsf{H}_1 expected information (see Section 8.2.1), and \mathbf{Q} is, by construction, an oblique projection. To make \mathbf{Q} a true projection (and the covariance Equation 10.31 non-negative-definite), lavResiduals() internally forces observed_information = "h1", overriding the user’s choice for this single computation. The element-wise standardized residuals are then r_{pp'}^{S} = e_{pp'}/\sqrt{[\widehat{\text{Var}} (\mathbf{e})]_{(pp'),(pp')}}, which is asymptotically standard normal.

The variant "standardized_mplus" follows the simpler subtractive formula used in older Mplus and LISREL versions:

\widehat{\text{Var}}(\mathbf{e})_{\text{Mplus}} \;=\; \widehat{\text{Var}}(\mathbf{s}) - \boldsymbol{\Delta}(\hat{\boldsymbol{\vartheta}})\, \widehat{\text{Var}}(\hat{\boldsymbol{\vartheta}})\, \boldsymbol{\Delta}(\hat{\boldsymbol{\vartheta}})^{\prime}. \tag{10.32}

This expression can yield a negative diagonal element when the parameter covariance is large relative to the sample-stat covariance, in which case the corresponding standardized residual is returned as NA. The projection-based formula Equation 10.31 avoids this and is the recommended choice; "standardized_mplus" is retained for consistency with results from those programs.

For the running CFA model, the standardized residuals localize the misfit:

lavResiduals(fit, type = "standardized", summary = FALSE, zstat = FALSE)$cov
       x1     x2     x3     x4     x5     x6     x7     x8     x9
x1  0.000                                                        
x2 -1.996  0.000                                                 
x3 -0.997  2.689  0.000                                          
x4  2.679 -0.284 -1.899  0.000                                   
x5 -0.359 -0.591 -4.157  1.545  0.000                            
x6  2.155  0.681 -0.711 -2.588  0.942  0.000                     
x7 -3.773 -3.654 -1.858  0.865 -0.842 -0.326  0.000              
x8 -1.380 -1.119 -0.300 -2.021 -1.099 -0.641  4.823  0.000       
x9  4.077  1.606  3.518  1.225  1.701  1.423 -2.325 -4.132  0.000

The largest absolute values flag the cells where the model fails to reproduce the data. In this dataset, the largest values involve the speed indicators: x7 and x8 are more strongly related than the model allows (4.82), while x9 is under-predicted by x1 and x3 (4.08 and 3.52) and over-predicted by x8 (-4.13), consistent with the well-known cross-loading of x9 on the visual factor (see the modification indices in Section 10.11).

10.8.4 The summary table

When summary = TRUE (the default for lavResiduals()), the function returns a data.frame summarizing the size of the residuals, separately for the covariance block (cov), the mean block (mean, if any), and the total. For the default type = "cor_bentler", this is a structured implementation of Maydeu-Olivares (2017)’s framework. We describe the entries in detail because they appear together in the output and because their formulas connect the SRMR/CRMR to a formal inferential framework.

Let \mathbf{e} denote the vector of standardized residuals (in the chosen type’s metric), \boldsymbol{\Xi} its asymptotic covariance matrix (computed as in Equation 10.31 but rescaled to the chosen metric via the appropriate covariance-to-correlation derivative matrices), and let p^{\star} be the number of summed elements (as in Table 10.3). Define

T = \mathbf{e}^{\prime}\mathbf{e}, \qquad \tau_{1} = \mathrm{tr}(\boldsymbol{\Xi}), \qquad \tau_{2} = \mathrm{tr}(\boldsymbol{\Xi}^{2}), \qquad v = \mathbf{e}^{\prime}\boldsymbol{\Xi}\,\mathbf{e}.

The sample SRMR (or CRMR, depending on the metric) is then

\widehat{\mathrm{SRMR}} = \sqrt{T/p^{\star}}, \tag{10.33}

reproducing Equation 10.17. As Maydeu-Olivares (2017, eq. 22) shows, this estimator is positively biased: in finite samples it over-estimates the population SRMR, with the bias decreasing as N grows and as the misfit grows. lavaan therefore reports, alongside the sample value, the unbiased estimator \hat{\iota} (Maydeu-Olivares, 2017, eq. 24):

\hat{k} = 1 - \frac{\tau_{2} + 2v}{4 T^{2}}, \qquad \hat{\iota} = \frac{1}{\hat{k}}\, \sqrt{\frac{\max(T - \tau_{1},\ 0)}{p^{\star}}}. \tag{10.34}

The factor \hat{k}^{-1} is a small bias-correction; the more important correction is the subtraction of \tau_{1} = \mathrm{tr}(\boldsymbol{\Xi}) inside the square root, which removes the contribution of sampling noise to the squared residuals (under the null hypothesis of exact fit, the expected value of T is exactly \tau_{1}). The truncation \max(\cdot, 0) keeps \hat{\iota} real when T < \tau_{1}; in that case the unbiased SRMR is reported as zero. The corresponding columns in the lavaan output are usrmr (or ucrmr, urmr).

The asymptotic standard error of \hat{\iota} is (Maydeu-Olivares, 2017, eq. 26)

\widehat{\mathrm{ASE}}(\hat{\iota}) \;=\; \sqrt{\frac{1}{\hat{k}^{2}}\, \frac{\tau_{2} + 2v}{2\,p^{\star}\,T}}, \tag{10.35}

reported as usrmr.se. From Equation 10.35, lavaan derives a (1-\alpha) confidence interval \hat{\iota} \pm z_{\alpha/2}\, \widehat{\mathrm{ASE}}(\hat{\iota}) (usrmr.ci.lower, usrmr.ci.upper), with \alpha = 0.10 (90% CI) by default to match the RMSEA convention (the level can be changed via the usrmr_ci_level argument). Two one-sided tests are also produced. The close-fit test, H_{0}: \iota \le \iota_{0}, with \iota_{0} = 0.05 by default (reported as usrmr.closefit.h0.value, and settable via the usrmr_close_h0 argument), has p-value 1 - \Phi(z) where

z_{\text{close}} = \frac{\hat{\iota} - \iota_{0}}{\widehat{\mathrm{ASE}}(\hat{\iota})} \tag{10.36}

(usrmr.closefit.z, usrmr.closefit.pvalue). The exact-fit test, H_{0}: \iota = 0, uses the moments of the biased sample SRMR under exact fit (Maydeu-Olivares, 2017, eqs. 28–30):

\mu_{T^{\star}} = \sqrt{\tau_{1}/p^{\star}}\, \frac{4\tau_{1}^{2} - \tau_{2}}{4\tau_{1}^{2}}, \qquad \sigma_{T^{\star}}^{2} = \frac{\tau_{2}}{2\,p^{\star}\,\tau_{1}},

and computes z_{\text{exact}} = \max(\widehat{\mathrm{SRMR}} - \mu_{T^{\star}}, 0)/\sigma_{T^{\star}}, with p-value 1 - \Phi(z_{\text{exact}}) (srmr.exactfit.z, srmr.exactfit.pvalue). The truncation by zero is a lavaan convention to keep the resulting z non-negative.

Both tests are one-sided: a small p-value rejects the null in favor of more misfit than the threshold permits. The close-fit test is the direct analog of Equation 10.11 for the RMSEA, and is the more useful of the two in routine practice.

10.8.5 The remaining arguments

The remaining arguments are described briefly below.

  • se (default FALSE). When TRUE, the per-element asymptotic standard errors of the chosen residual type are returned as cov.se (and mean.se) elements of the output list. They share the same metric as the residuals themselves. (The summary table computes these standard errors internally in any case, but they are only returned as list elements when se = TRUE.)

  • zstat (default TRUE). When TRUE, per-element z-statistics r_{pp'}/\widehat{\mathrm{ASE}}(r_{pp'}) are returned (cov.z, mean.z). These can be compared informally against \pm 1.96 to flag suspicious cells, but no overall multiple-testing correction is applied.

  • summary (default TRUE). When FALSE, the summary data.frame is suppressed; only the residual matrices and (if requested) their SEs and z-statistics are returned.

  • h1_acov (default "unstructured"). Selects which estimate of \widehat{\text{Var}}(\mathbf{s}) is used in Equation 10.31. With "unstructured", lavaan uses the standard unrestricted-model estimate, evaluated at the sample (co)variances (e.g., for normal continuous data, 2\,\mathbf{D}^{+}(\mathbf{S}\otimes \mathbf{S}) \,\mathbf{D}^{+\prime}/N). With "structured", the same formula is evaluated at the model-implied \hat{\boldsymbol{\Sigma}}. The unstructured choice is the standard one and is what Maydeu-Olivares (2017) derives the formulas for; the structured option is retained for compatibility with older Mplus output. If a user-supplied asymptotic covariance matrix was passed via the NACOV argument when fitting the model, that matrix is used regardless of h1_acov.

  • h1 (default NULL). Allows the user to supply an alternative unrestricted (\mathsf{H}_1) model, either a fitted lavaan object or a list of moments, whose implied statistics are then used as the “observed” summary statistics in place of the default unrestricted estimates.

  • combine (default FALSE). When TRUE (and there are multiple groups or levels), the per-block summary tables are replaced by a single overall table that pools the residual elements across all blocks; the pooled ACOV correctly accounts for the correlation between blocks (across the levels of a multilevel model, and across groups whenever cross-group equality constraints couple the parameter estimates).

  • elementwise (default TRUE). When FALSE, the element-wise residual matrices are omitted and only the summary information is returned.

  • usrmr_ci_level (default 0.90) and usrmr_close_h0 (default 0.05). Set the confidence level of the reported CI and the null-hypothesis value of the close-fit test for the unbiased uRMR/uSRMR/uCRMR summaries, mirroring the rmsea_ci_level and rmsea_close_h0 options of fitMeasures().

  • output (default "list"). When "table", the function returns a sorted data.frame in which each row is one residual element, sorted by absolute magnitude, with optional se/z columns. The rows cover not only the (co)variances, but also the means/intercepts, thresholds, and (for conditional_x = TRUE) the regression slopes. The maximum_number argument caps the number of rows shown (0 = all). The value "text" (alias "pretty") prints, for each element group and block, a small table with the n_largest largest residuals, followed by the residual summary tables in the style of the fit-measures output. The same text output can be appended to the regular summary() output via summary(fit, residuals = TRUE).

  • add_type, add_labels, add_class, drop_list_single_group are cosmetic options controlling the structure and printing of the returned object.

The more complex data types are covered as well. The per-element SEs, z-statistics, and the (u)RMR/(u)SRMR/(u)CRMR summary tables are available for categorical models (on the polychoric/polyserial correlation and threshold scale, including mixed continuous/ordinal data), for conditional_x = TRUE (both continuous and categorical; the regression slopes are standardized and reported in a separate res.slopes block, which also enters the summary “total”), and for multilevel models, with or without multiple groups (per-level within/between residuals and summary tables; with multiple groups, the output blocks are named by group and level, and the combined summary keeps the cross-group covariance of the estimates that equality constraints induce). Note that the multilevel SRMR values reported by fitMeasures() (srmr, srmr_within, srmr_between; see Section 10.5) are still computed separately, by the dedicated SRMR code (Section 10.12).

10.8.6 residuals() and resid()

For backward compatibility with the wider R ecosystem, lavaan defines S4 methods for the generic residuals() and its alias resid():

residuals(object, type = "raw", labels = TRUE)
resid(object, type = "raw")

Both default to type = "raw" (note the contrast with lavResiduals(), which defaults to "cor_bentler"); both accept the same type values listed in Table 10.4; neither produces the summary table or the asymptotic z-statistics (they share the computational core of lavResiduals(), with those extras switched off; see the implementation notes at the end of this chapter). They are convenient for quick inspection but should not be used as the primary residual diagnostic; lavResiduals() supersedes them.

One special case is reserved: residuals(object, type = "casewise") (or any of "case", "obs", "observations", "ov") bypasses the summary-statistic residuals entirely and returns casewise residuals, discussed next.

10.8.7 Casewise residuals

Setting type = "casewise" (or any of "case", "obs", "observations", "ov") on residuals() switches from the summary-statistic residuals above to casewise residuals, the SEM analog of regression residuals. For each observation i, lavaan computes

\hat{\mathbf{e}}_{i} \;=\; \mathbf{y}_{i} \;-\; \hat{\mathbf{y}}_{i}, \tag{10.37}

where \hat{\mathbf{y}}_{i} is the model-implied conditional expectation of \mathbf{y}_{i}, computed via lavPredict() using its default factor-score method ("EBM", the regression method). The result is an N_{g} \times P matrix per group:

case_res <- residuals(fit, type = "casewise")
head(case_res)
              x1         x2          x3         x4         x5          x6
[1,] -0.78476111  2.1145436 -1.27902732 -0.5900298  1.5625666 -0.77247081
[2,]  0.34804425 -0.8654489 -0.16153326 -0.3815174 -0.2132922  0.03807294
[3,]  0.32562704 -0.4166066  0.17992479 -0.1886218 -0.5065335 -0.02298953
[4,] -0.02177789  1.4298545  0.44372950 -0.4127271  0.1388925  0.22587905
[5,]  0.31346845 -1.1078364 -1.07206670 -0.2719913 -0.2044578  0.49907816
[6,]  0.37430733 -1.1009122 -0.01737775 -0.7310908  0.1396569 -0.09682378
              x7          x8          x9
[1,] -0.85610502  0.15034805  0.92046586
[2,] -1.02878697 -0.01512811  1.86605321
[3,] -0.08445971 -0.63524188 -0.04835181
[4,] -0.91456497  0.09308802 -0.21955294
[5,] -0.68457938  0.54362432  0.33237018
[6,] -0.54692944  0.28651133  1.35923030

Casewise residuals are restricted to models fitted on the raw data and to continuous observed variables; categorical models are not supported by residuals() (although the categorical case is covered by the M-distance diagnostics of Section 10.10, which work with expected casewise residuals of the latent responses). They are the basic building block for the regression-style diagnostics advocated by Maydeu-Olivares (2017, p. 552) (residual-vs-fitted plots, normality QQ-plots, leverage diagnostics) and for the outlier-detection procedure of Yuan and Hayashi (2010) discussed in Section 10.10. The latter uses a slightly different variant of Equation 10.37, one in which \hat{\mathbf{y}}_{i} is constructed from Bartlett factor scores rather than from regression-method scores, because Bartlett scores have an orthogonality property that lets leverage and outlier status be cleanly separated. The substantive treatment of casewise residuals is therefore deferred to that section.

10.9 Frequency tables for ordinal data: lavTables()

When the endogenous variables are ordinal (chapter 14), the residuals of Section 10.8 compare thresholds and polychoric correlations with their model-implied values. The data themselves, however, are frequency tables: one-way tables of category counts for each variable, two-way tables for each pair, and, in principle, the full table of response patterns. Misfit can be inspected at any of these levels by comparing observed and model-implied proportions (Jöreskog & Moustaki, 2001), and the lavTables() function does so. It takes either a fitted lavaan object or a data frame; with a data frame, only the observed proportions and the statistics of the unrestricted model are available.

For the examples we use the ordinal version of the Holzinger–Swineford data from chapter 14, in which each of the nine test scores is cut at its quartiles into four ordered categories, and fit the usual three-factor model with the default WLSMV estimator:

HSord <- HolzingerSwineford1939
for (v in paste0("x", 1:9)) {
  HSord[[v]] <- cut(HolzingerSwineford1939[[v]],
                    breaks = quantile(HolzingerSwineford1939[[v]],
                                      probs = seq(0, 1, 0.25)),
                    include.lowest = TRUE, labels = FALSE)
  HSord[[v]] <- ordered(HSord[[v]])
}
fit_ord <- cfa(model, data = HSord, ordered = TRUE)

The dimension argument selects the level: 1L for one-way tables, 2L (the default) for two-way tables, and 0L for response patterns. The type argument selects what a row of the output represents: a cell ("cells", the default) or a whole table ("table"). The statistic argument selects the columns; its default depends on the other two arguments and on whether a model was fitted. All statistics exist in two versions: the plain version compares the observed proportions with the proportions implied by the fitted model, and the version with suffix .un compares them with the proportions implied by the unrestricted model of chapter 14, that is, by the sample thresholds and the sample polychoric correlations. The first version measures the misfit of the structural equation model; the second measures only the misfit of the latent response formulation itself (bivariate normality of the latent responses) for that table, and is the only one available for a data frame.

10.9.1 One-way tables

With dimension = 1L, each row is one category of one variable:

head(lavTables(fit_ord, dimension = 1L), 8)
  id lhs rhs nobs obs.freq obs.prop est.prop X2
1  1  x1   1  301       82    0.272    0.272  0
2  1  x1   2  301       82    0.272    0.272  0
3  1  x1   3  301       65    0.216    0.216  0
4  1  x1   4  301       72    0.239    0.239  0
5  2  x2   1  301       90    0.299    0.299  0
6  2  x2   2  301       82    0.272    0.272  0
7  2  x2   3  301       60    0.199    0.199  0
8  2  x2   4  301       69    0.229    0.229  0

The columns give the variable (lhs), the category (rhs), the number of observations, the observed frequency and proportion, the model-implied proportion, and the Pearson statistic of the cell. The model-implied proportion of category c of variable p is the probability that the latent response falls between the model-implied thresholds, \Phi(\hat{\tau}_{pc}) - \Phi(\hat{\tau}_{p,c-1}). Since the thresholds are free parameters in this model, these proportions reproduce the observed ones exactly, and the one-way statistics are zero. They become informative when thresholds are constrained, as in a multiple-group model with group_equal = "thresholds" (Section 14.6.2): the one-way tables then show, group by group and category by category, where the equality constraints produce misfit. With a data frame as input, the thresholds of the unrestricted model can be requested with statistic = "th.un"; the last category gets +\infty.

10.9.2 Two-way tables

With dimension = 2L and the default type = "cells", each row is one cell of one two-way table:

cells <- lavTables(fit_ord, dimension = 2L)
dim(cells)
[1] 576  10
head(cells, 6)
  id lhs rhs nobs row col obs.freq obs.prop est.prop    X2
1  1  x1  x2  301   1   1       32    0.106    0.128 1.064
2  1  x1  x2  301   2   1       26    0.086    0.087 0.001
3  1  x1  x2  301   3   1       21    0.070    0.051 2.207
4  1  x1  x2  301   4   1       11    0.037    0.034 0.050
5  1  x1  x2  301   1   2       26    0.086    0.076 0.409
6  1  x1  x2  301   2   2       27    0.090    0.080 0.335

There are 36 pairs with 4 \times 4 = 16 cells each, hence 576 rows. The id column numbers the tables, row and col index the cell, and the three proportions columns and the statistic follow. The model-implied proportion of cell (a, b) of the pair (p, p^{\prime}) is the rectangle probability of the bivariate normal distribution, Equation 14.5 of Section 14.4.2, evaluated at the model-implied thresholds of the two variables and the model-implied correlation of their latent responses, [\boldsymbol{\Sigma}(\boldsymbol{\hat{\vartheta})}]_{pp^{\prime}}; the unrestricted version uses the sample thresholds and the sample polychoric correlation instead. With observed proportion p_{ab} and implied proportion \hat{\pi}_{ab}, the cell statistics are

X^2_{ab} = N\, \frac{(p_{ab} - \hat{\pi}_{ab})^2}{\hat{\pi}_{ab}}, \qquad G^2_{ab} = 2 N\, p_{ab} \log \frac{p_{ab}}{\hat{\pi}_{ab}}, \tag{10.38}

the Pearson and likelihood-ratio contributions of the cell. The X^2 contributions are nonnegative; the G^2 contributions are positive when a cell is over-represented and negative when it is under-represented, and undefined for an empty cell. Both sum, over the cells of a table, to the corresponding statistic of the table.

With type = "table", each row summarizes one pair. The default columns are the Pearson statistic and its average over the cells; more can be requested:

tab <- lavTables(fit_ord, dimension = 2L, type = "table",
                 statistic = c("cor.un", "cor", "X2", "G2", "RMSEA"))
head(tab[order(tab$G2, decreasing = TRUE), ], 5)
    lhs rhs nobs df   cor cor.un     X2     G2 RMSEA
529  x7  x8  301  8 0.276  0.479 17.867 20.019 0.071
257  x3  x5  301  8 0.224  0.103 19.990 18.292 0.065
305  x3  x8  301  8 0.141  0.174 14.891 15.447 0.056
465  x5  x9  301  8 0.208  0.287 14.288 13.974 0.050
193  x2  x7  301  8 0.112 -0.033 13.849 13.898 0.049

Here cor.un is the sample polychoric correlation of the pair, cor the model-implied one, X2 and G2 the table totals, and RMSEA a table-level root mean square error of approximation,

\mathrm{RMSEA}_{pp^{\prime}} = \sqrt{\max\left(0,\; \frac{G^2_{pp^{\prime}} - df_{pp^{\prime}}}{N\, df_{pp^{\prime}}} \right)}, \qquad df_{pp^{\prime}} = (C_p - 1)(C_{p^{\prime}} - 1) - 1, \tag{10.39}

where the degrees of freedom count the cells of the table minus the margins (reproduced by the thresholds) minus the one correlation. The further statistics X2.average, X2.nlarge, X2.plarge (and their G2 versions) give the average cell contribution, the number of cells whose contribution exceeds x2_min (default 3; g2_min for the G^2 versions), and the proportion of such cells. With p_value = TRUE, each statistic is accompanied by a p-value from the chi-square distribution with df_{pp^{\prime}} degrees of freedom. These p-values should be read as rough guides: the statistics of the P(P-1)/2 tables are not independent, the model-implied correlation of a pair is not a free parameter of that table, and the limited-information estimators do not fit the tables directly. The point of the table view is comparative: to find the pairs that contribute most to the misfit of the model.

In the example, the pair x7–x8 stands out, with the largest G^2 and a model-implied correlation (0.28) well below the sample value (0.48). This is the same residual association that the modification indices (Section 10.11) flag for the continuous version of these data, and modindices(fit_ord) places the residual covariance x7 ~~ x8 among the two largest indices here as well. The cell view shows where in the table the excess lies. With output = "table", the cells of each pair are arranged as a matrix, one list element per pair, inside a list with one element per group:

lavTables(fit_ord, dimension = 2L, output = "table",
          statistic = "G2")[[1]]$x7_x8
       1      2      3      4
1 29.915 -5.414 -2.048 -9.259
2 -7.494  2.808 -1.014  7.680
3 -5.674  3.334  3.472 -0.190
4 -7.504 -0.108 -0.190 11.706

The (1, 1) and (4, 4) cells (the lowest and the highest category on both items) carry large positive contributions: more respondents than the model predicts are in the same extreme category on both speed items, which is exactly what a positive residual correlation between them describes. The unrestricted statistics for the same pair are unremarkable (statistic = "G2.un" gives 7.7 on 8 degrees of freedom, close to the median over all pairs), so the problem lies with the model, not with the bivariate normality of the latent responses.

For a data frame, the same tables are available without a model, which is a convenient way to screen ordinal data before a model is fitted: the categorical= argument names the ordinal variables (all variables in the data frame are used), and group= a grouping variable. Only the .un statistics exist in this case:

lavTables(HSord[paste0("x", 1:3)], dimension = 2L, type = "table",
          categorical = paste0("x", 1:3),
          statistic = c("cor.un", "X2.un", "G2.un"))
   lhs rhs nobs df cor.un X2.un G2.un
1   x1  x2  301  8  0.307 7.651 7.651
17  x1  x3  301  8  0.384 6.205 6.075
33  x2  x3  301  8  0.319 5.167 5.048

10.9.3 Response patterns

With dimension = 0L (or type = "pattern"), each row is one observed response pattern, with its observed frequency and proportion, its model-implied probability, and the G^2 and X^2 contributions. The model-implied probability of a full pattern is a P-dimensional rectangle probability of the multivariate normal distribution of the latent responses, computed by numerical integration, and this is a different kind of quantity from the one- and two-way statistics: it uses the full information in the data, whereas the WLS and PML estimators only fit the univariate and bivariate margins. lavaan warns about this mismatch when a limited-information estimator was used. With nine items and four categories there are 4^9 possible patterns and only 301 cases, so the observed table is extremely sparse (nearly every observed pattern occurs once), and the pattern-level statistics are of little diagnostic value here; they are informative for small numbers of binary items. The three pairwise-likelihood fit statistics of Barendse et al. (2016) (lavTablesFitCf(), lavTablesFitCm(), lavTablesFitCp()) build on these pattern and pairwise tables for the PML estimator of Section 14.7.

10.10 Casewise outliers

The fit measures of Section 10.2 and the residual analysis of Section 10.8 both summarize misfit at the level of the summary statistics. But misfit at that level is itself driven by the individual observations: a small number of unusual cases can inflate variances, distort covariances, and cause the chi-square test to reject a model that would otherwise fit the bulk of the data well. Identifying such cases is the goal of casewise outlier diagnostics.

10.10.1 Outliers, leverage observations, and Mahalanobis distance

The terminology of Yuan and Hayashi (2010) transposes the familiar concepts from regression diagnostics to the SEM setting. For the prototypical factor model

\mathbf{y}_{i} \;=\; \boldsymbol{\mu}\;+\; \boldsymbol{\Lambda}\, \boldsymbol{\eta}_{i} \;+\; \boldsymbol{\epsilon}_{i}, \qquad i = 1, \ldots, N, \tag{10.40}

three categories of unusual observations can be distinguished:

  • A leverage observation is a case whose latent factor scores \boldsymbol{\eta}_{i} are far from the bulk of the data. Whether the observation is good (it lies on the latent regression “surface” that the rest of the data establish) or bad depends on the size of its measurement-error component \boldsymbol{\epsilon}_{i}.
  • An outlier is a case whose measurement-error component \boldsymbol{\epsilon}_{i} is large, regardless of where its factor scores lie. A bad leverage observation is therefore both a leverage observation and an outlier; a good leverage observation is a leverage observation but not an outlier.
  • A normal case has both small \boldsymbol{\epsilon}_{i} and a factor-score vector close to the rest of the data.

In regression, leverage observations affect the standard errors of the coefficients but not their bias; bad leverage observations and outliers bias the coefficient estimates. Exactly the same logic applies in SEM, with one important complication: \boldsymbol{\eta}_{i} and \boldsymbol{\epsilon}_{i} are both unobservable. The diagnostic must therefore be based on estimates \hat{\boldsymbol{\eta}}_{i} and \hat{\boldsymbol{\epsilon}}_{i}, specifically the Bartlett (or “ML”) factor scores

\hat{\boldsymbol{\eta}}_{i} \;=\; \bigl(\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\,\boldsymbol{\Lambda}\bigr)^{-1} \boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\,(\mathbf{y}_{i} - \boldsymbol{\mu}) \tag{10.41}

(see Lawley and Maxwell (1971); the topic of factor-score prediction is taken up in detail in Chapter 13), and the corresponding casewise residual

\hat{\boldsymbol{\epsilon}}_{i} \;=\; \mathbf{y}_{i} - (\boldsymbol{\mu}+ \boldsymbol{\Lambda}\,\hat{\boldsymbol{\eta}}_{i}) \;=\; \bigl[\mathbf{I} - \boldsymbol{\Lambda}\,(\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\boldsymbol{\Lambda})^{-1}\, \boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\bigr]\,(\mathbf{y}_{i} - \boldsymbol{\mu}). \tag{10.42}

The Bartlett predictor is the unique linear estimator of \boldsymbol{\eta}_{i} for which \hat{\boldsymbol{\epsilon}}_{i} is orthogonal to the column space of \boldsymbol{\Lambda} (Yuan & Hayashi, 2010, Appendix A): this orthogonality is what allows the casewise residual to be interpreted as an estimate of \boldsymbol{\epsilon}_{i} alone, without confounding from the factor scores. The “regression” factor-score predictor (also discussed in Chapter 13) does not enjoy this property; the resulting casewise residual is contaminated by \hat{\boldsymbol{\eta}}_{i}.

A Mahalanobis distance (M-distance) measures how far a vector is from its mean, in units of its standard error, taking the covariance among its elements into account. For a generic K-vector \mathbf{u} with mean zero and covariance \boldsymbol{\Omega},

d \;=\; \sqrt{\mathbf{u}^{\prime}\,\boldsymbol{\Omega}^{-1}\,\mathbf{u}}. \tag{10.43}

When \mathbf{u} \sim \mathcal{N}(\mathbf{0}, \boldsymbol{\Omega}), the squared M-distance d^{2} follows a chi-square distribution with K degrees of freedom. This reference distribution is what allows large M-distances to be flagged as unusual.

10.10.2 M-distance for factor scores: leverage

The M-distance of the factor-score vector \hat{\boldsymbol{\eta}}_{i} measures how far the predicted latent position of case i lies from the centroid of the latent space, and is thus the natural quantification of leverage. For the model in Equation 10.40, the asymptotic covariance of the Bartlett factor scores is (Lawley & Maxwell, 1971, p. 110)

\boldsymbol{\Omega}_{\hat{\boldsymbol{\eta}}} \;=\; \boldsymbol{\Psi}\;+\; \bigl(\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\,\boldsymbol{\Lambda}\bigr)^{-1}, \tag{10.44}

where \boldsymbol{\Psi}= \text{Var}(\boldsymbol{\eta}) is the latent variance matrix. The leverage M-distance is then

d_{f,i} \;=\; \sqrt{\hat{\boldsymbol{\eta}}_{i}^{\prime}\, \boldsymbol{\Omega}_{\hat{\boldsymbol{\eta}}}^{-1}\,\hat{\boldsymbol{\eta}}_{i}}. \tag{10.45}

In lavaan, this quantity is exposed via lavInspect():

mdist_fs <- lavInspect(fit, "mdist_fs")
head(mdist_fs)
[1] 1.506946 1.992908 2.344090 1.220469 1.033306 2.427433
length(mdist_fs)
[1] 301

The output is a numeric vector of length N (one value per observation). Internally it is computed via lavPredict(fit, type = "lv", method = "ML", mdist = TRUE). Asking for "mdist2_fs" instead returns the squared values, which are directly comparable to the \chi^{2}_{M} reference distribution; here M is the number of latent factors.

10.10.3 M-distance for casewise residuals: outlier status

The analogous M-distance for the casewise residual \hat{\boldsymbol{\epsilon}}_{i} is the natural quantification of outlier status. There is one subtlety: the residual vector \hat{\boldsymbol{\epsilon}}_{i} is, by construction, P-dimensional but lies in a (P- M)-dimensional subspace (the orthogonal complement of the column space of \boldsymbol{\Lambda}). Its sample covariance \boldsymbol{\Omega}_{\hat{\boldsymbol{\epsilon}}} is therefore singular, and the M-distance must be taken in the lower-dimensional subspace where this covariance is invertible.

lavaan handles this by an eigendecomposition. Let \boldsymbol{\Omega}_{\hat{\boldsymbol{\epsilon}}} = (\mathbf{I} - \boldsymbol{\Lambda} \mathbf{A}_B)\,\hat{\boldsymbol{\Sigma}}\,(\mathbf{I} - \boldsymbol{\Lambda}\mathbf{A}_B)^{\prime}, where \mathbf{A}_B = (\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\boldsymbol{\Lambda})^{-1}\, \boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1} is the Bartlett factor score coefficient matrix (Section 13.2.3). Compute the eigendecomposition of \boldsymbol{\Omega}_{\hat{\boldsymbol{\epsilon}}} and let \mathbf{E} be the P\times (P- M) matrix whose columns span the non-null eigenspace. The M-distance for the residual is then

d_{r,i} \;=\; \sqrt{(\mathbf{E}^{\prime}\hat{\boldsymbol{\epsilon}}_{i})^{\prime}\, \bigl(\mathbf{E}^{\prime}\boldsymbol{\Omega}_{\hat{\boldsymbol{\epsilon}}}\,\mathbf{E}\bigr)^{-1}\, (\mathbf{E}^{\prime}\hat{\boldsymbol{\epsilon}}_{i})}. \tag{10.46}

Under multivariate normality of the original observations, d_{r,i}^{2} is asymptotically chi-square distributed with P- M degrees of freedom. lavaan exposes the (non-squared) values through lavInspect() as well:

mdist_resid <- lavInspect(fit, "mdist_resid")
head(mdist_resid)
[1] 4.0654198 2.7926391 0.9352564 1.7717102 2.1243874 2.2558576

The squared values are accessible via "mdist2_resid".

Both M-distances are also defined for (partly) ordered categorical data: each distance is replaced by its expected value over the region of the latent-response vector \mathbf{y}^{\star} that is consistent with the observed response pattern, with \mathbf{y}^{\star} normally distributed under the model, and the region defined by the model-implied thresholds. Observed continuous variables are conditioned on, and missing values are integrated out. The expectation is approximated by Monte Carlo integration (the mdist_draws argument of lavPredict(), 2000 by default, sets the number of draws per distinct response pattern); when all variables are continuous, the computation reduces exactly to the classic distances. One subtlety is that, for categorical data, the expected distance E[d] returned by "mdist_fs"/"mdist_resid" is no longer the square root of the expected squared distance E[d^{2}] returned by "mdist2_fs"/"mdist2_resid", so lavaan computes both directly.

10.10.4 Two diagnostic plots

The two M-distances together support two complementary diagnostic plots, proposed by Yuan and Hayashi (2010). The first contrasts d_{f,i} against d_{r,i} in a single scatter, with critical lines at the square roots of the relevant chi-square quantiles; the second is a QQ-style plot of the ordered d_{r,i} against the quantiles of the reference chi distribution.

10.10.5 Leverage versus outliers

The first plot places the leverage M-distance on the horizontal axis and the outlier M-distance on the vertical axis. The four quadrants defined by the two critical lines have a direct interpretation:

  • Bottom left: small d_{f,i} and small d_{r,i}. These are normal cases.
  • Bottom right: large d_{f,i} and small d_{r,i}. These are good leverage observations. They lie far from the centroid of the latent space but are reproduced well by the model.
  • Top left: small d_{f,i} and large d_{r,i}. These are outliers in the strict sense: they are not extreme on the latent scale, but the model fails to reproduce their observed pattern.
  • Top right: large d_{f,i} and large d_{r,i}. These are bad leverage observations, extreme on the latent scale and poorly reproduced. These have the largest potential impact on parameter estimates and on the chi-square test.

For the running CFA model, Figure 10.1 draws this plot from the two M-distance vectors returned by lavInspect() (the R code is listed in Section 10.12.1).

Figure 10.1: Leverage versus outliers plot for the Holzinger–Swineford CFA. Critical lines are drawn at the square roots of the 99th percentiles of \chi^2_{M} and \chi^2_{P-M}, with M = 3 factors and P = 9 observed variables.

The critical lines are drawn at the square roots of the 1-\alpha quantile of the relevant chi-square distribution; with \alpha = 0.01, they identify the most outlying 1\% of cases under the assumption of normality. Values close to the lines are also labelled, to avoid the arbitrary classification that would result from using the cutoff alone (cases just above and just below a critical value should be considered together, not on opposite sides of a line). The labels are row numbers of the analyzed data (identical to the dataset rows here, since there are no missing values); cases plotted in red are bad leverage observations and warrant the closest attention.

10.10.6 Chi-square quantile plot

The second plot is a QQ-plot of the sorted residual M-distances against the quantiles of the chi distribution with P- M degrees of freedom. Departures from the (dashed) 45-degree line indicate that the empirical distribution of d_{r,i} does not match the normal-theory reference. The interpretive emphasis is on clusters of points that detach from the main mass, rather than on individual cases above a threshold. Figure 10.2 shows the plot for the running CFA model (code in Section 10.12.1).

Figure 10.2: QQ-plot of casewise residual M-distances against the quantiles of \sqrt{\chi^2_{P-M}}. The five largest residuals are labelled with the corresponding case index. A cluster of points pulling away from the bulk would suggest a group of related outliers; a single isolated point at the top is consistent with a lone outlier.

A short, isolated cluster of points at the top of the plot suggests a small number of outliers; a long tail that departs systematically from the line over roughly the upper third of the cases suggests a heavier-than-normal residual distribution, and calls the assumption of multivariate normality into question. Cases at the very top of the plot are the ones most likely to drive the chi-square statistic, and merit individual inspection: they may be coding errors, substantively unusual cases, or the sign of an unmodelled mechanism.

10.10.7 Robust estimation: the sample_cov_robust argument

A well-known problem with moment-based diagnostics is the masking effect: a small group of outliers can pull the sample covariance matrix \mathbf{S} towards itself in such a way that none of the individual M-distances d_{i} = \sqrt{(\mathbf{y}_{i} - \bar{\mathbf{y}})^{\prime}\, \mathbf{S}^{-1}\,(\mathbf{y}_{i} - \bar{\mathbf{y}})} stands out. If the estimates of \boldsymbol{\mu} and \boldsymbol{\Sigma} that go into computing the M-distances are themselves driven by the outliers, the diagnostic loses its power to detect them.

The standard remedy is to compute \boldsymbol{\mu} and \boldsymbol{\Sigma} using a robust M-estimator that downweights cases with large M-distance. Yuan and Hayashi (2010) advocate the Huber-type weights (Huber, 1964):

w_{1}(d) = \begin{cases} 1 & d \le \rho \\ \rho/d & d > \rho \end{cases}, \qquad w_{2}(d) = \frac{w_{1}(d)^{2}}{\kappa}, \tag{10.47}

with the tuning constant \rho chosen as \sqrt{\chi^{2}_{1-\varphi}(P)} for some small contamination fraction \varphi (e.g. \varphi = 0.05), and \kappa a consistency correction that ensures \hat{\boldsymbol{\Sigma}} is asymptotically unbiased under multivariate normality. The estimates are then obtained by an iteratively-reweighted scheme:

\hat{\boldsymbol{\mu}}^{(j+1)} = \frac{\sum_{i} w_{1}(d_{i}^{(j)})\,\mathbf{y}_{i}} {\sum_{i} w_{1}(d_{i}^{(j)})}, \qquad \hat{\boldsymbol{\Sigma}}^{(j+1)} = \frac{1}{N}\sum_{i} w_{2}(d_{i}^{(j)})\,(\mathbf{y}_{i} - \hat{\boldsymbol{\mu}}^{(j+1)})\, (\mathbf{y}_{i} - \hat{\boldsymbol{\mu}}^{(j+1)})^{\prime}, \tag{10.48}

iterated until \hat{\boldsymbol{\mu}} and \hat{\boldsymbol{\Sigma}} stabilize. lavaan uses the default settings \varphi = 0.05 (probability mass for the tuning) and a maximum of 200 iterations. The result is a Huber-type M-estimator that downweights, rather than removes, the cases beyond the cutoff.

Setting sample_cov_robust = TRUE in any of cfa(), sem(), or lavaan() causes lavaan to:

  1. compute the robust (\hat{\boldsymbol{\mu}}, \hat{\boldsymbol{\Sigma}}) from the raw data using Equation 10.48,
  2. pass these as the sample mean and sample covariance to the standard estimation pipeline, and
  3. fit the SEM using the regular ML (or GLS) procedure on the robust sample moments.

The fitted parameter estimates then inherit the robustness properties of \hat{\boldsymbol{\Sigma}} (see Yuan & Zhong, 2008 for a formal discussion); both the factor-score M-distances and the residual M-distances are subsequently computed using these robust quantities, which neutralizes the masking effect.

fit_robust <- cfa(model, data = HolzingerSwineford1939,
                  sample_cov_robust = TRUE)
mdist_resid_robust <- lavInspect(fit_robust, "mdist_resid")

The option is currently restricted to single-level, listwise-complete data with continuous observed variables, conditional_x = FALSE, no sampling weights, and ML or GLS estimation; the relevant restrictions are checked when the options are processed. (Multiple groups are allowed; the robust moments are then computed per group.) For data with missing values, with categorical observed variables, or with a clustered/multilevel structure, the user is responsible for combining a robust covariance estimator with the SEM fit by other means (for example, by computing \hat{\boldsymbol{\Sigma}} outside lavaan and passing it via sample_cov = ...).

A practical workflow following Yuan and Hayashi (2010) is therefore: fit the model with sample_cov_robust = TRUE, inspect the two diagnostic plots above, identify (and inspect) the cases flagged as bad-leverage or outlier, decide on substantive grounds whether to retain or remove them, and re-fit the model with regular ML on the trimmed dataset. The robust fit and the trimmed-ML fit should be broadly consistent if the outlier set has been correctly identified.

10.11 Modification indices

The diagnostics in Section 10.8 and Section 10.10 are descriptive: they describe how well the fitted model reproduces the data, but they do not directly point to which parameters of the model could be changed to improve fit. Modification indices fill that gap. For each parameter that is currently fixed in the model (typically fixed at zero: a constrained loading, a missing residual covariance, an absent direct effect), the modification index estimates the decrease in the chi-square test statistic that would follow from freeing that parameter. The companion expected parameter change (EPC) provides an estimate of the value that the freed parameter would take. Together, these two quantities suggest candidate changes to the model specification.

The modindices() function in lavaan computes modification indices and EPCs only for parameters that are fixed at a constant (zero or otherwise) in the user’s model. It does not handle equality constraints: the impact of releasing one or more constraints of the form a == b cannot be assessed via modindices(). For that, the function lavTestScore() should be used; it implements the multivariate score test for the joint release of an arbitrary set of constraints (see Section 11.4 for the score test in general). lavaan emits a warning when modindices() is called on a model that contains equality constraints.

10.11.1 Rationale and the connection with the score test

A modification index is a score (Lagrange-multiplier) test statistic for the hypothesis that one currently-fixed parameter equals its fixed value (Buse, 1982; Saris et al., 1987; Sörbom, 1989). Suppose the user-specified model has free parameter vector \boldsymbol{\vartheta}^{(1)} of length T and fixed parameter \vartheta^{(2)}_{q}, and consider the extended model in which \vartheta^{(2)}_{q} is freed alongside the existing \boldsymbol{\vartheta}^{(1)}. The score test compares the gradient of the log-likelihood of the extended model, evaluated at the constrained estimate (\hat{\boldsymbol{\vartheta}}^{(1)}, \vartheta^{(2)}_{q,0}), against zero. If freeing the parameter would substantially improve the fit, the gradient with respect to \vartheta^{(2)}_{q} at the constrained estimate will be far from zero.

Concretely, partition the expected information matrix of the extended model conformably with (\boldsymbol{\vartheta}^{(1)}, \vartheta^{(2)}),

\mathbf{A}_{E} \;=\; \begin{pmatrix} \mathbf{A}_{E,11} & \mathbf{A}_{E,12} \\ \mathbf{A}_{E,21} & \mathbf{A}_{E,22} \end{pmatrix},

let \mathbf{u} = \partial \log L / \partial \vartheta^{(2)}\,\big|_{\hat{\boldsymbol{\vartheta}}^{(1)}, \vartheta^{(2)}_{0}} be the gradient of the log-likelihood with respect to the fixed-parameter block, evaluated at the constrained MLE, and let

\mathbf{V} \;=\; \mathbf{A}_{E,22} \;-\; \mathbf{A}_{E,21}\,\mathbf{A}_{E,11}^{-1}\,\mathbf{A}_{E,12} \tag{10.49}

denote the Schur complement (Saris et al., 1987). The univariate modification index for the q-th fixed parameter is then

\mathrm{MI}_{q} \;=\; N\,\frac{u_{q}^{2}}{V_{qq}}, \tag{10.50}

where V_{qq} is the q-th diagonal element of \mathbf{V}. Under the null hypothesis that \vartheta^{(2)}_{q} = \vartheta^{(2)}_{q,0} in the population, \mathrm{MI}_{q} has an asymptotic chi-square distribution with one degree of freedom. The motivation for the name “modification index” is the asymptotic equivalence (under the null) of the score test, the Wald test, and the likelihood-ratio test (Buse, 1982): the value of \mathrm{MI}_{q} approximates the decrease in X^{2}_{\mathrm{ML}} that would be observed if the model were re-estimated with \vartheta^{(2)}_{q} freed.

The expected parameter change is the one-step Newton update of \vartheta^{(2)}_{q,0} in the direction of the score:

\mathrm{EPC}_{q} \;=\; \frac{u_{q}}{V_{qq}}. \tag{10.51}

It estimates the value that the freed parameter would take after re-estimation. Note that, by combining Equation 10.50 and Equation 10.51,

\mathrm{MI}_{q} \;=\; N\,V_{qq}\,\mathrm{EPC}_{q}^{2} \;=\; \biggl(\frac{\mathrm{EPC}_{q}}{\sigma_{q}}\biggr)^{2}, \qquad \sigma_{q} = \frac{1}{\sqrt{N\,V_{qq}}}, \tag{10.52}

so the MI is the squared ratio of the EPC to its asymptotic standard error \sigma_{q}. This relationship, noted by Saris et al. (1987) and re-emphasized by Saris et al. (2009, eq. 6), is what allows the standard error of any unestimated parameter (and a confidence interval for it) to be computed post hoc from the MI and the EPC, without re-fitting.

10.11.2 The standardized EPC

The raw EPC is on the original scale of the parameter, which is inconvenient for substantive interpretation when the variances of the involved variables differ. lavaan reports three standardized variants, constructed by applying the same standardization rules used for estimated parameters (see Chapter 12):

  • sepc.lv: \mathrm{EPC}_{q} standardized only with respect to the latent variables (used mostly for unstandardized factor loadings of a model with implicitly-scaled latent variables).
  • sepc.all: \mathrm{EPC}_{q} standardized with respect to both latent and observed variables, the analog of Std.all in the summary() output.
  • sepc.nox: like sepc.all, but observed exogenous variables are not standardized (matches Std.nox).

sepc.all is the most directly interpretable for the typical use case: for a fixed-to-zero residual covariance, sepc.all is on the scale of a correlation; for a fixed-to-zero cross-loading, it is on the scale of a standardized loading. Conventional thresholds for “substantively relevant” misspecifications, such as the value 0.1 for standardized structural parameters and 0.4 for factor loadings recommended by Saris et al. (2009), apply directly to this scale.

10.11.3 The modindices() function

The user-visible function is modindices(); two aliases, modificationIndices() and modificationindices(), have identical effect. Internally, lavaan first constructs an enlarged parameter table in which every parameter that could be added to the model is freed (and initialized at its current fixed value); the expected information matrix and gradient of this extended model are computed, and the formulas Equation 10.50–Equation 10.51 are applied row by row. The extended-model device means that no actual re-fitting is necessary: a single linear-algebra pass over the partitioned information matrix delivers the MI and EPC for every fixed parameter at once.

The output is a data frame with one row per candidate parameter. A few arguments shape it. The screening arguments sort, minimum_value and maximum_number order the rows by decreasing mi, drop rows below a threshold, and cap the number of rows; modindices(fit, sort = TRUE, maximum_number = 10) returns the ten largest modification indices. The op argument restricts the rows to a given operator: op = "~~" returns only residual covariances, op = "=~" only cross-loadings. When standardized = TRUE (the default), the standardized EPCs sepc.lv, sepc.all and sepc.nox accompany the raw epc. The arguments power, delta, alpha and high_power govern the power-of-the-test analysis of Section 10.11.5, which is switched off by default. The remaining arguments select the information matrix of Equation 10.49 (the expected information by default) and control the removal of rows for parameters that are already free or whose index is undefined; see ?modindices for the full list.

The modification index in the mi column follows a chi-square distribution with one degree of freedom only if the estimator is asymptotically efficient and its distributional assumptions hold: ML with normal data, for example, or WLS. For estimators that are not asymptotically efficient (DWLS and ULS, and therefore also "WLSMV" and "ULSMV"), and for ML with nonnormal data, the expected value of the index under the null hypothesis can be larger or smaller than one, and even the ranking of the candidate parameters can be affected. Whenever the fitted object provides the ingredients for a sandwich-type covariance matrix (robust standard errors or a scaled test statistic were requested, as for "MLM", "MLR", "WLSMV" and "ULSMV"), the output therefore contains an additional column mi.scaled: the scaled score test of Satorra (2000), which for a single parameter coincides with the generalized (robust) version, computed for all candidate parameters at once. It equals the X2.scaled value that the univariate table of lavTestScore() reports for the same parameter (see below, and Section 11.4.5). When it is present, mi.scaled is the column on which to judge the significance of a candidate parameter; mi is kept for comparability with other software. The EPC columns are the same in both cases. For the running example fitted with the MLM estimator (the fit_mlm object of Section 10.3.1), the four largest modification indices are:

modindices(fit_mlm, sort = TRUE, maximum_number = 4)
      lhs op rhs     mi mi.scaled    epc sepc.lv sepc.all sepc.nox
30 visual =~  x9 36.411    25.891  0.577   0.519    0.515    0.515
76     x7 ~~  x8 34.145    25.404  0.536   0.536    0.859    0.859
28 visual =~  x7 18.631    18.791 -0.422  -0.380   -0.349   -0.349
78     x8 ~~  x9 14.946    15.132 -0.423  -0.423   -0.805   -0.805

For the running CFA model, the ten largest modification indices are:

modindices(fit, sort = TRUE, maximum_number = 10)
       lhs op rhs     mi    epc sepc.lv sepc.all sepc.nox
30  visual =~  x9 36.411  0.577   0.519    0.515    0.515
76      x7 ~~  x8 34.145  0.536   0.536    0.859    0.859
28  visual =~  x7 18.631 -0.422  -0.380   -0.349   -0.349
78      x8 ~~  x9 14.946 -0.423  -0.423   -0.805   -0.805
33 textual =~  x3  9.151 -0.272  -0.269   -0.238   -0.238
55      x2 ~~  x7  8.918 -0.183  -0.183   -0.192   -0.192
31 textual =~  x1  8.903  0.350   0.347    0.297    0.297
51      x2 ~~  x3  8.532  0.218   0.218    0.223    0.223
59      x3 ~~  x5  7.858 -0.130  -0.130   -0.212   -0.212
26  visual =~  x5  7.441 -0.210  -0.189   -0.147   -0.147

The largest MI typically points to either a substantively meaningful mis-specification (e.g., a missing cross-loading of an indicator on a non-targeted factor) or a parameter whose release would bring the model close to non-identification and that does not correspond to a substantively defensible modification. The sepc.all column is what the user should focus on: an MI of 30 with sepc.all = 0.05 is a significant misspecification of substantively trivial size, whereas an MI of 30 with sepc.all = 0.5 is a substantively relevant one.

10.11.4 Releasing equality constraints with lavTestScore()

When the model contains equality constraints (for example, metric-invariance constraints on factor loadings across groups, or homogeneity constraints on residual variances), their effect on the chi-square statistic cannot be assessed by modindices(), which is designed for fixed-to-constant parameters. Instead, the function lavTestScore() should be used (Section 11.4 gives the full treatment; here we only summarize the arguments that matter in this context). By default, lavTestScore() performs a single multivariate score test for the joint release of all equality constraints currently in the model. The release argument, a vector of constraint indices in the order in which they appear in parTable(fit), limits the test to the listed constraints. The univariate argument (TRUE by default) additionally returns the per-constraint univariate score tests, which play the same role as modindices() does for fixed parameters: each is a chi-square(1) test for the hypothesis that releasing that single constraint would not change the fit. With epc = TRUE, the expected parameter change (after release) is also returned. See ?lavTestScore for the remaining arguments, including add, which tests the addition of new parameters through model syntax rather than through constraint indices.

Robust versions of the total score test are reported automatically whenever the fitted object provides the ingredients for a sandwich-type covariance matrix, that is, when robust standard errors or a scaled test statistic were requested. Following Satorra (2000), three versions are added: a mean-scaled statistic (score.scaled), a mean-and-variance adjusted statistic with fractional degrees of freedom (score.adjusted), and the generalized, asymptotically distribution-free statistic (score.robust). The univariate (and cumulative) score tests are then accompanied by scaled counterparts in an X2.scaled column. See also Section 9.8.

lavTestScore() is the appropriate function to assess, for example, partial measurement invariance: fit a model with full invariance, then call lavTestScore(fit, univariate = TRUE) to identify which loading constraints, if released, would yield the largest improvements.

10.11.5 The power = TRUE argument

Modification indices share the same sample-size dependence as the chi-square test from which they are derived: in large samples, even substantively trivial misspecifications produce significant MIs, and in small samples, even substantively important misspecifications can fail to reach significance. Saris et al. (1987) proposed that this problem can be diagnosed, on a parameter-by-parameter basis, by computing the power of the score test against a meaningful alternative, and using the combination of MI-significance and power-against-meaningful-alternative as the basis for a five-cell classification of each fixed parameter.

The power calculation requires a single user-supplied input: a value \delta representing the smallest substantively meaningful misspecification, the size of the parameter that the user would want the test to detect. Under a local alternative \vartheta^{(2)}_{q} = \vartheta^{(2)}_{q,0} + \delta, the asymptotic distribution of the modification index is non-central chi-square with one degree of freedom and noncentrality parameter (Saris et al., 2009, eq. 9)

\mathrm{ncp}_{q} \;=\; \biggl(\frac{\delta}{\sigma_{q}}\biggr)^{2}. \tag{10.53}

Combining this with Equation 10.52 gives the form actually computed by lavaan, which expresses ncp purely in terms of the observable MI and EPC:

\mathrm{ncp}_{q} \;=\; \frac{\mathrm{MI}_{q}}{\mathrm{EPC}_{q}^{2}}\,\delta^{2}. \tag{10.54}

The power of an \alpha-level test is then

\mathrm{Power}_{q} \;=\; 1 - F_{\chi^{2}_{1}(\mathrm{ncp}_{q})}\bigl(\chi^{2}_{1-\alpha}(1)\bigr), \tag{10.55}

where \chi^{2}_{1-\alpha}(1) is the upper-\alpha critical value of the central chi-square distribution with one degree of freedom, and F_{\chi^{2}_{1}(\mathrm{ncp})}(\cdot) is the CDF of the non-central chi-square with one df and noncentrality \mathrm{ncp}.

The arguments of modindices() that govern this calculation are:

  • power = FALSE (default). When TRUE, the power columns are appended to the output, and a decision column is added. The significance part of the decision is based on the mi.scaled column when it is available (Section 10.11.3), and on the mi column otherwise.
  • delta = 0.1. The user-supplied \delta in Equation 10.54. The default value of 0.1 matches the recommendation of Saris et al. (2009) for standardized structural parameters. For factor loadings, a larger value (e.g., 0.4) is more appropriate; for residual correlations, 0.1 is reasonable.
  • alpha = 0.05. The Type-I error level used to set the rejection threshold of the score test.
  • high_power = 0.75. The threshold above which a power value is considered “high” for the purposes of the Saris et al. (2009) classification.
  • delta_std = FALSE (default). Selects the metric in which delta is interpreted: the unstandardized metric of the epc column when FALSE, the fully standardized metric of the sepc.all column when TRUE.

The EPC in Equation 10.54 enters in the unstandardized metric, so by default \delta is interpreted in the unstandardized metric of the parameter in question, which depends on the scales of the observed variables. The recommendations of Saris et al. (2009) (0.1 for structural parameters, 0.4 for loadings), however, refer to the standardized scale. Setting delta_std = TRUE interprets \delta on the sepc.all scale: lavaan converts it to the unstandardized metric of each parameter before computing the noncentrality parameter and the power (the standardized value is linear in the parameter, given the model-implied variances), and the decision column then compares the standardized EPC with \delta. The values "std.lv" and "std.nox" select the sepc.lv and sepc.nox scales instead. Whenever power = TRUE, only one standardized EPC column is shown: sepc.all by default, or the column matching delta_std. One caveat: with the default cov_std = TRUE, residual covariances are standardized by the residual variances rather than by the total variances, so standardizing the data before fitting is not equivalent to delta_std = TRUE for those rows.

The decision column reports a five-cell classification based on Saris et al. (2009, Table 6):

Table 10.5: Decision rule for power = TRUE in modindices(), following Saris et al. (2009, Table 6).
MI Power vs. \delta EPC vs. \delta decision Interpretation
not significant low (< high_power) not used (i) inconclusive
significant low not used **(m)** misspecification present
not significant high (\ge high_power) not used (nm) no misspecification
significant high \lvert\mathrm{EPC}\rvert \le \delta epc:nm EPC small: no relevant misspecification
significant high \lvert\mathrm{EPC}\rvert > \delta *epc:m* EPC large: relevant misspecification

The two extreme cases that the Saris et al. (2009) framework is designed to identify are:

  • the “small sample” case, a significant MI obtained with low power (**(m)**): the test detects a problem despite limited sensitivity, so the misspecification is almost certainly real;
  • the “large sample” case, a significant MI obtained with high power but a small EPC (epc:nm): the test detects a difference that is too small to matter substantively, and respecification is not warranted.

The remaining two cells are interpreted directly: significant MI combined with high power and a substantively large EPC (*epc:m*) points to a real and substantively relevant misspecification, while a non-significant MI combined with high power ((nm)) provides positive evidence that the constraint is consistent with the data. The inconclusive cell ((i)) indicates that the data do not contain enough information to decide either way for that particular constraint; nothing further can be said until a larger sample is available.

For the running example, asking for power gives:

modindices(fit, power = TRUE, sort = TRUE, maximum_number = 10)
       lhs op rhs     mi    epc sepc.all delta   ncp power decision
30  visual =~  x9 36.411  0.577    0.515   0.1 1.094 0.182  **(m)**
76      x7 ~~  x8 34.145  0.536    0.859   0.1 1.187 0.193  **(m)**
28  visual =~  x7 18.631 -0.422   -0.349   0.1 1.047 0.176  **(m)**
78      x8 ~~  x9 14.946 -0.423   -0.805   0.1 0.835 0.150  **(m)**
33 textual =~  x3  9.151 -0.272   -0.238   0.1 1.240 0.200  **(m)**
55      x2 ~~  x7  8.918 -0.183   -0.192   0.1 2.671 0.373  **(m)**
31 textual =~  x1  8.903  0.350    0.297   0.1 0.725 0.136  **(m)**
51      x2 ~~  x3  8.532  0.218    0.223   0.1 1.791 0.268  **(m)**
59      x3 ~~  x5  7.858 -0.130   -0.212   0.1 4.643 0.577  **(m)**
26  visual =~  x5  7.441 -0.210   -0.147   0.1 1.689 0.255  **(m)**

This output is the practical realization of Saris et al. (2009)’s recommendation: rather than acting on every “significant” modification index (and risk model-data overfit), or ignoring all of them (and risk missing real misspecifications), the user should focus on parameters flagged as *epc:m* (a high-power, large-EPC misspecification) and consult the underlying substantive theory before deciding to free them.

A standard caution applies whenever modification indices are used to guide model respecification: each freed parameter is data-driven and will mechanically improve the fit; the post-respecification model is no longer the model that was originally hypothesized, and its standard errors and tests are conditional on the data-dependent path that led to it. Modification indices are most defensible when used as a forward search to flag candidate misspecifications for later replication on a fresh dataset, not as an automated path to a “good-fitting” model on the same data.

10.12 Implementation notes

This section collects details that are tied to the current implementation of lavaan (the R package, version 0.7-4) rather than to the concepts of the main text. Internal file and function names may change or move at any release, while everything reachable through the user interface stays put. Table 10.6 maps the fit measures and diagnostics of this chapter to their source files.

Table 10.6: Source files behind the fit measures and diagnostics.
Topic File(s)
baseline (independence) model generation (lav_object_independence(); cached in the @baseline slot, also per level for the partially saturated fits) lav_object_generate.R
fit-measure dispatch lav_fit_measures.R
level-specific fit: lav_object_fit_by_level() fits the partially saturated model and its baseline model for each level, reusing the data, sample statistics and \mathsf{H}_1 slots of the original fit. Each auxiliary fit is first attempted with the regular optimizer; if that fails (the saturated level of a baseline model often has a nearly singular covariance matrix, which sends quasi-Newton steps into the inadmissible region), it is repeated with the EM algorithm when the model allows it (a single group, ML, no explicit constraints), for the baseline models with a loose stopping rule, since their test statistic is typically huge. Warnings of the auxiliary fits are suppressed; only a failure to converge is reported lav_fit_by_level.R
custom baseline models: lav_fit_check_baseline() validates a user-supplied baseline (estimator and test must match; refitted otherwise). An experimental baseline_type = "nested" option derives the baseline from the user’s parameter table (directed effects, covariances and latent variances fixed to zero, everything else, including equality constraints, kept), so that it is nested by construction; its handling of mean structures is not settled and the option is not documented in lavOptions() lav_fit_cfi.R
lav_object_generate.R
incremental fit indices (CFI/TLI family) lav_fit_cfi.R
SRMR family: lav_fit_srmr_lavobject() selects the variant for the plain srmr name (Bentler with or without the mean part, depending on the presence of a mean structure) lav_fit_srmr.R
residuals: lavResiduals() is a wrapper around lav_residuals(), which the residuals() method also calls, leaving se, zstat and summary at their FALSE defaults (resid() delegates to residuals()); asymptotic covariance of the sample statistics from lav_model_h1_acov(); covariance-to-correlation derivatives in lav_deriv_cov2cor_b() lav_residuals.R
lav_model_h1_information.R
lav_func_deriv.R
frequency tables for ordinal data: lavTables() dispatches to lav_tables_oneway(), lav_tables_pairwise_cells(), lav_tables_pairwise_table() and lav_tables_pattern(); model-implied cell proportions from lav_tables_pairwise_model_pi(), unrestricted ones from lav_tables_pairwise_sample_pi(); pattern probabilities via mnormt::sadmvn() in lav_tables_resp_pi(); the C_F, C_M and C_P statistics lav_tables.R
ctr_pairwise_fit.R
Huber-type robust (co)variances (lav_cov_huber()) lav_samplestats_robust.R
modification indices: the extended model of lav_object_extended(); the scaled version (mi.scaled) uses the meat matrix of lav_test_meat() lav_modification.R
lav_object_generate.R
lav_test_satorra2000.R
option checks for fit-related settings lav_options.R

10.12.1 Code for the diagnostic plots

The two outlier plots of Section 10.10.4 are not produced by a lavaan function; they are drawn with base R graphics from the M-distance vectors that lavInspect() returns. The code below produces Figure 10.1. The critical lines are drawn at the square roots of the 1-\alpha chi-square quantiles, and cases near or beyond a line are labelled with their row number (green for good leverage observations and outliers, red for bad leverage observations).

nvar <- length(lavNames(fit, "ov"))
nfac <- length(lavNames(fit, "lv"))

mdist_fs    <- lavInspect(fit, "mdist_fs")
mdist_resid <- lavInspect(fit, "mdist_resid")

alpha <- 0.01
q_f <- sqrt(qchisq(1 - alpha, df = nfac))
q_r <- sqrt(qchisq(1 - alpha, df = nvar - nfac))

# one row per case; flag the cases near or beyond the critical lines
q_r2 <- q_r - 0.05; q_f2 <- q_f - 0.05
md <- data.frame(case = seq_along(mdist_fs),
                 fs = mdist_fs, resid = mdist_resid)
md$bad  <- md$fs >= q_f2 & md$resid >= q_r2
md$good <- (md$fs >= q_f2 | md$resid >= q_r2) & !md$bad

XLIM <- range(c(md$fs[is.finite(md$fs)], q_f)) * c(1, 1.05)
YLIM <- range(c(md$resid[is.finite(md$resid)], q_r)) * c(1, 1.05)
tinyplot(resid ~ fs, data = md, xlim = XLIM, ylim = YLIM,
         xlab = "M-distance factor scores (leverage)",
         ylab = "M-distance casewise residuals (outliers)")
tinyplot_add(type = type_vline(q_f))
tinyplot_add(type = type_hline(q_r))
if (any(md$good)) tinyplot_add(type = "text", labels = case, subset = good,
                               pos = 4, col = "darkgreen")
if (any(md$bad))  tinyplot_add(type = "text", labels = case, subset = bad,
                               pos = 4, col = "red")

The QQ-plot of Figure 10.2 reuses nvar, nfac and mdist_resid from the previous block, and labels the five largest residual M-distances with their case index:

out <- sort.int(mdist_resid, index.return = TRUE)
N <- length(mdist_resid)
qq <- data.frame(
  theoretical = sqrt(qchisq(ppoints(N), df = nvar - nfac)),
  observed    = out$x,       # sorted M-distances
  case        = out$ix)      # their case indices

nlabel <- 5L
qq$top <- seq_len(N) > N - nlabel
tinyplot(observed ~ theoretical, data = qq,
         xlab = "Quantiles of (square root of) chi-square distribution",
         ylab = "M-distance casewise residuals (outliers)")
tinyplot_add(type = "abline", lty = 2)
tinyplot_add(type = "text", labels = case, subset = top,
             pos = 2, col = "grey30")

  1. For the multigroup case, the value of K used in lavaan corresponds to the first group only. This is a known caveat of the current implementation.↩︎