9  The lavaan object

9.1 Introduction

When a model is fitted with one of the lavaan model-fitting functions (lavaan(), cfa(), sem(), or growth()), the result is typically assigned to a variable. By convention, this variable is named fit, but any valid R name can be used. The returned value is an object of class "lavaan", and throughout this book we refer to it as the lavaan object.

HS_model2 <- '
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
'
fit <- cfa(HS_model2, data = HolzingerSwineford1939)
class(fit)[1]
[1] "lavaan"

The lavaan object stores everything that lavaan computed in the course of fitting the model. Its contents mirror the steps of the fitting process: the original call and the full set of resolved options (appendix F); the data as processed by lavaan (Section 5.5) and the sample statistics computed from it, together with the \mathsf{H}_1 model (Section 5.7); the parameter table (Chapter 3) and the model matrices that were built from it; the results of the optimization (the point estimates, convergence information, and timing); the model-implied moments; the variance–covariance matrix of the estimates and the test statistics (Section 8.4, Section 8.5); the fit of the baseline model, needed for the incremental fit indices (Section 10.2); the bootstrap draws, when bootstrapping was requested; and a version stamp of the package that created the object. Several of these components are complex objects in their own right (the data container and the sample statistics container, in particular), each with its own internal layout. The implementation notes at the end of this chapter (Section 9.13) describe the layout of these components in the current release.

Although the internal components of a lavaan object can be reached directly, users should rarely need to do this. Instead, lavaan provides a rich collection of methods and functions that take the lavaan object as their first argument and return the quantity of interest in a labeled, user-facing form. The distinction is important. The internal layout is the current container: the way in which lavaan organizes its results internally, in this version, in R. The accessor functions are the contract: they are documented, they are kept stable across versions, and they are the interface that the more than two hundred packages built on lavaan are expected to program against. When lavaan’s internals change, as they have repeatedly in the past and will again, code written against the accessors is not affected. Code written against the internal layout is affected. The remainder of this chapter describes the contract.

9.2 Overview of methods

The methods and functions that operate on a lavaan object can be divided into two broad families:

  1. Standard R methods: methods for generic functions that come with base R or with the stats package. Users familiar with lm(), glm(), or nlme() will recognize most of them: summary(), coef(), vcov(), fitted(), residuals(), predict(), logLik(), nobs(), anova(), and update().

  2. lavaan-specific functions: functions that are exported by the lavaan package and have no counterpart in base R. These typically have names that start with lav (e.g., lavInspect(), lavPredict(), lavResiduals()) or that are descriptive of the quantity returned (e.g., parameterEstimates(), fitMeasures(), modindices()).

Table 9.1 lists the standard R methods, and Table 9.2 lists the lavaan-specific functions.

Table 9.1: Standard R methods defined for the "lavaan" class.
Method Description Section
show() Short summary printed when the object name is typed at the prompt Section 9.11.4
summary() Detailed text summary: parameter estimates, fit measures, etc. Section 9.3
coef() Vector of free parameter estimates Section 9.4.1
vcov() Variance–covariance matrix of the free parameter estimates Section 9.5
fitted() / fitted.values() Model-implied summary statistics Section 9.6.1
residuals() / resid() Difference between observed and model-implied summary statistics Section 9.6.2
predict() Factor scores for the (regular) latent variables Section 9.10
logLik() Log-likelihood at the final estimated parameters Section 9.11
nobs() (Effective) sample size Section 9.11
anova() Likelihood ratio test of nested models Section 9.8
update() Refit the model after modifying the call Section 9.11
AIC(), BIC() Information criteria (inherited via logLik()) Section 9.11
Table 9.2: lavaan-specific functions that operate on a lavaan object.
Function Description Section
parameterEstimates() Parameter table with estimates, standard errors, z-statistics, p-values, confidence intervals Section 9.4
standardizedSolution() Standardized parameter estimates (std.lv, std.all, std.nox) with standard errors Section 9.4
parameterTable() / parTable() The internal parameter table Section 9.4
fitMeasures() / fitmeasures() Fit measures (CFI, RMSEA, SRMR, …) Section 9.7
modindices() / modificationIndices() Modification indices and expected parameter changes Section 9.9
lavPredict() Factor scores with additional options (method, transform, mdist, …) Section 9.10
lavPredictY() Model-based predictions of the observed y-variables, given the observed x-variables Section 9.10
lavResidualsY() Casewise residuals of the y-variables (observed minus predicted values) Section 9.10
lavResiduals() Detailed residual analysis (raw, normalized, standardized, …) Section 9.6.2
lavEffects() Total, indirect, and direct effects (mediation analysis) (see Section 8.4.15)
lavScores() Casewise score vectors Section 9.10
lavTest() Recompute or request additional test statistics Section 9.8
lavTestLRT() Likelihood ratio test of nested models (extended anova()) Section 9.8
lavTestScore() Score (Lagrange multiplier) test Section 9.8
lavTestWald() Wald test of (combinations of) parameters Section 9.8
lavInspect() / inspect() User-friendly access to internal quantities Section 9.12
lavTech() “Technical” version of lavInspect() (no labels, full matrices) Section 9.12
lavBootstrap() Bootstrap any function of a fitted model (see Section 8.4.12)

The sections below discuss each family in turn.

9.3 The summary() method

For most users, summary() is the most frequently used method: it prints a human-readable report of the fitted model, combining information about the estimation procedure, the model test statistics, the parameter estimates, and (optionally) fit indices, modification indices, and standardized estimates.

A minimal call shows the default output:

summary(fit)
lavaan 0.7-4 ended normally after 28 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        13

  Number of observations                           301

Model Test User Model:
                                                      
  Test statistic                                24.361
  Degrees of freedom                                 8
  P-value (Chi-square)                           0.002
                                                      
  Browne's residual (NT model-based) test             
  Test statistic                                24.488
  Degrees of freedom                                 8
  P-value (Chi-square)                           0.002

Parameter Estimates:

  Standard errors                             Standard
  Information                                 Expected
  Information saturated (h1) model          Structured

Latent Variables:
                   Estimate  Std.Err  z-value  P(>|z|)
  visual =~                                           
    x1                1.000                           
    x2                0.559    0.105    5.301    0.000
    x3                0.708    0.118    6.004    0.000
  textual =~                                          
    x4                1.000                           
    x5                1.111    0.065   16.996    0.000
    x6                0.925    0.055   16.703    0.000

Covariances:
                   Estimate  Std.Err  z-value  P(>|z|)
  visual ~~                                           
    textual           0.414    0.074    5.562    0.000

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .x1                0.536    0.129    4.155    0.000
   .x2                1.125    0.103   10.965    0.000
   .x3                0.863    0.095    9.085    0.000
   .x4                0.369    0.048    7.735    0.000
   .x5                0.449    0.059    7.662    0.000
   .x6                0.356    0.043    8.263    0.000
    visual            0.822    0.158    5.188    0.000
    textual           0.981    0.112    8.745    0.000

The output is organized in three blocks:

  1. A header describing the estimator, the optimizer, the number of free parameters, the sample size, and the model test statistics. In the current default for ML estimation, there are two of them: the standard chi-square test and Browne’s residual-based test (Section 8.5.10, which also lists the settings in which the second test is not available). Any further test statistics requested with the test= argument are added here as well.

  2. Parameter estimates in three sub-blocks corresponding to the measurement part (=~), the structural part (~, ~~), and any defined parameters (:=).

  3. Optional sections (fit measures, R^2, modification indices, …) that are added on request.

The most commonly used arguments are summarized in Table 9.3.

Table 9.3: Most commonly used arguments of the summary() method for lavaan objects.
Argument Default Effect
header TRUE Print the header block
fit_measures FALSE Append a block of fit indices
residuals FALSE Append the residuals section (as produced by lavResiduals())
estimates TRUE Print the parameter estimates block
ci FALSE Add confidence intervals to the parameter table
standardized FALSE Add std.lv and std.all columns
rsquare FALSE Print R^2 for endogenous variables
modindices FALSE Append modification indices
nd 3L Number of decimal digits

A typical, more extensive call requests fit measures, standardized estimates, and R^2 values:

summary(fit, fit_measures = TRUE, standardized = TRUE, rsquare = TRUE)

Note that summary() does not print directly. Instead, it collects the components of the summary (the header, the parameter estimates, the fit measures, …) in a list-like object, returns that object invisibly, and leaves the printing to a separate print method. The separation between collecting the components of the summary and printing them allows users to capture, post-process, or programmatically extract specific blocks of the summary without re-running the printer.

s <- summary(fit, fit_measures = TRUE)
names(s)
s$pe          # parameter estimates as a data.frame
s$fit         # fit measures as a named vector

9.4 Inspecting parameter estimates

Several methods return information about the model parameters at different levels of detail and in different formats.

9.4.1 coef()

coef() returns the named numeric vector of free parameter estimates, in the same order as in the parameter table:

coef(fit)
      visual=~x2       visual=~x3      textual=~x5      textual=~x6 
           0.559            0.708            1.111            0.925 
          x1~~x1           x2~~x2           x3~~x3           x4~~x4 
           0.536            1.125            0.863            0.369 
          x5~~x5           x6~~x6   visual~~visual textual~~textual 
           0.449            0.356            0.822            0.981 
 visual~~textual 
           0.414 

By default, the elements are named after the parameters (visual=~x2, say), or after their user-defined labels when these were given; set labels = FALSE to obtain a vector without names. The optional argument type = "user" returns the full set of parameters, including fixed values:

coef(fit, type = "user")

9.4.2 parameterEstimates()

The function parameterEstimates() (with synonym lavParameterEstimates()) returns a data frame containing one row per parameter and columns for the estimate, standard error, z-statistic, p-value, and confidence interval bounds:

parameterEstimates(fit)
       lhs op     rhs   est    se      z pvalue ci.lower ci.upper
1   visual =~      x1 1.000 0.000     NA     NA    1.000    1.000
2   visual =~      x2 0.559 0.105  5.301      0    0.352    0.766
3   visual =~      x3 0.708 0.118  6.004      0    0.477    0.939
4  textual =~      x4 1.000 0.000     NA     NA    1.000    1.000
5  textual =~      x5 1.111 0.065 16.996      0    0.983    1.239
6  textual =~      x6 0.925 0.055 16.703      0    0.817    1.034
7       x1 ~~      x1 0.536 0.129  4.155      0    0.283    0.789
8       x2 ~~      x2 1.125 0.103 10.965      0    0.924    1.326
9       x3 ~~      x3 0.863 0.095  9.085      0    0.677    1.049
10      x4 ~~      x4 0.369 0.048  7.735      0    0.276    0.463
11      x5 ~~      x5 0.449 0.059  7.662      0    0.334    0.563
12      x6 ~~      x6 0.356 0.043  8.263      0    0.272    0.441
13  visual ~~  visual 0.822 0.158  5.188      0    0.511    1.132
14 textual ~~ textual 0.981 0.112  8.745      0    0.761    1.201
15  visual ~~ textual 0.414 0.074  5.562      0    0.268    0.559

The following arguments are among the most useful:

  • ci = FALSE suppresses the confidence interval columns; level controls the confidence level (default 0.95).
  • standardized = TRUE adds two columns (std.lv, std.all) with the corresponding standardized estimates.
  • rsquare = TRUE appends R^2 values for endogenous variables; these R^2 values are defined as 1 minus the standardized residual variances of the corresponding variables.
  • boot_ci_type selects the type of bootstrap confidence interval ("perc", "bca", "bca_simple", "norm", or "basic") when se = "bootstrap" was used during fitting.
  • remove_eq, remove_ineq, remove_def, remove_system_eq, remove_unused control which rows of the parameter table are included.
  • output = "text" prints the result in a more user-friendly format, similar to the parameter block of summary().

9.4.3 standardizedSolution()

The function standardizedSolution() returns a parameter table where the est.std column contains the standardized estimates and where, if possible, standard errors and a Wald-type confidence interval for the standardized estimates are provided (using the delta method described in Section 12.2):

standardizedSolution(fit)
       lhs op     rhs est.std    se      z pvalue ci.lower ci.upper
1   visual =~      x1   0.778 0.062 12.583      0    0.657    0.899
2   visual =~      x2   0.431 0.061  7.093      0    0.312    0.550
3   visual =~      x3   0.568 0.059  9.662      0    0.453    0.684
4  textual =~      x4   0.852 0.023 37.827      0    0.808    0.897
5  textual =~      x5   0.854 0.022 38.092      0    0.810    0.898
6  textual =~      x6   0.838 0.023 35.845      0    0.792    0.884
7       x1 ~~      x1   0.395 0.096  4.106      0    0.206    0.583
8       x2 ~~      x2   0.814 0.052 15.536      0    0.711    0.917
9       x3 ~~      x3   0.677 0.067 10.119      0    0.546    0.808
10      x4 ~~      x4   0.274 0.038  7.121      0    0.198    0.349
11      x5 ~~      x5   0.270 0.038  7.056      0    0.195    0.345
12      x6 ~~      x6   0.298 0.039  7.595      0    0.221    0.374
13  visual ~~  visual   1.000 0.000     NA     NA    1.000    1.000
14 textual ~~ textual   1.000 0.000     NA     NA    1.000    1.000
15  visual ~~ textual   0.461 0.064  7.195      0    0.335    0.586

The type argument controls which standardization is applied (Table 9.4):

Table 9.4: Standardization types accepted by standardizedSolution().
type Latent variables Observed variables
"std_lv" standardized not standardized
"std_all" standardized standardized
"std_nox" standardized standardized (except exogenous variables)

9.4.4 parameterTable() and friends

The internal parameter table of a fitted model can be obtained with parameterTable() (synonyms: parTable(), partable()). Unlike parameterEstimates(), this returns the raw internal table (see Chapter 3), including the column free (integer index of free parameters), start (starting values), est (estimates), user (user-supplied flag), and a few columns used internally:

parameterTable(fit)
   id     lhs op     rhs user block group free ustart exo label plabel start
1   1  visual =~      x1    1     1     1    0      1   0         .p1. 1.000
2   2  visual =~      x2    1     1     1    1     NA   0         .p2. 0.778
3   3  visual =~      x3    1     1     1    2     NA   0         .p3. 1.107
4   4 textual =~      x4    1     1     1    0      1   0         .p4. 1.000
5   5 textual =~      x5    1     1     1    3     NA   0         .p5. 1.133
6   6 textual =~      x6    1     1     1    4     NA   0         .p6. 0.924
7   7      x1 ~~      x1    0     1     1    5     NA   0         .p7. 0.679
8   8      x2 ~~      x2    0     1     1    6     NA   0         .p8. 0.691
9   9      x3 ~~      x3    0     1     1    7     NA   0         .p9. 0.637
10 10      x4 ~~      x4    0     1     1    8     NA   0        .p10. 0.675
11 11      x5 ~~      x5    0     1     1    9     NA   0        .p11. 0.830
12 12      x6 ~~      x6    0     1     1   10     NA   0        .p12. 0.598
13 13  visual ~~  visual    0     1     1   11     NA   0        .p13. 0.050
14 14 textual ~~ textual    0     1     1   12     NA   0        .p14. 0.050
15 15  visual ~~ textual    0     1     1   13     NA   0        .p15. 0.000
     est    se
1  1.000 0.000
2  0.559 0.105
3  0.708 0.118
4  1.000 0.000
5  1.111 0.065
6  0.925 0.055
7  0.536 0.129
8  1.125 0.103
9  0.863 0.095
10 0.369 0.048
11 0.449 0.059
12 0.356 0.043
13 0.822 0.158
14 0.981 0.112
15 0.414 0.074

9.5 Variance-covariance of the estimates: vcov()

The (estimated) sampling variance–covariance matrix of the free parameter estimates is returned by vcov():

vcov(fit)

By default (type = "free"), the matrix covers the free parameters only. With type = "user" (alias "joint"), the joint sampling variance–covariance matrix of the free and the user-defined (:=) parameters is returned; the parameter names then match those used by coef().

The standardized argument allows the variance–covariance matrix to be requested on the standardized scale:

vcov(fit, standardized = "std_all")

The same matrix is also returned by lavInspect(fit, "vcov").

9.6 Fitted moments and residuals

9.6.1 fitted() and fitted.values()

fitted() (alias fitted.values()) returns the model-implied summary statistics: typically the mean vector \hat{\boldsymbol{\mu}} and the covariance matrix \hat{\boldsymbol{\Sigma}}, but also thresholds, slopes, or polychoric correlations if the model has them. The result is a (named) list with components such as cov, mean, and th:

fitted(fit)
$cov
      x1    x2    x3    x4    x5    x6
x1 1.358                              
x2 0.459 1.382                        
x3 0.582 0.325 1.275                  
x4 0.414 0.231 0.293 1.351            
x5 0.460 0.257 0.325 1.090 1.660      
x6 0.383 0.214 0.271 0.908 1.009 1.196

For a multiple-group analysis, that list is nested inside an outer list with one element per group; for a single-group model, the outer wrapper is dropped automatically.

9.6.2 residuals() and lavResiduals()

residuals() (alias resid()) returns the difference between the observed and the model-implied summary statistics, on a scale selected by the type argument ("raw", "cor_bentler", "cor_bollen", "normalized", "standardized", "standardized_mplus", or "casewise", among others). The lavaan-specific lavResiduals() returns a richer object: the residual matrices on the chosen scale together with element-wise 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:

lavResiduals(fit)
$type
[1] "cor.bentler"

$cov
       x1     x2     x3     x4     x5     x6
x1  0.000                                   
x2 -0.038  0.000                            
x3 -0.002  0.095  0.000                     
x4  0.067 -0.016 -0.065  0.000              
x5 -0.013 -0.030 -0.146  0.005  0.000       
x6  0.056  0.026 -0.022 -0.010  0.004  0.000

$cov.z
       x1     x2     x3     x4     x5     x6
x1  0.000                                   
x2 -3.236  0.000                            
x3 -0.224  2.941  0.000                     
x4  2.653 -0.381 -1.873  0.000              
x5 -0.518 -0.682 -4.187  1.637  0.000       
x6  2.111  0.613 -0.627 -2.932  1.164  0.000

$summary
                           cov
srmr                     0.047
srmr.se                  0.008
srmr.exactfit.z          2.987
srmr.exactfit.pvalue     0.001
usrmr                    0.042
usrmr.se                 0.012
usrmr.ci.lower           0.022
usrmr.ci.upper           0.061
usrmr.closefit.h0.value  0.050
usrmr.closefit.z        -0.701
usrmr.closefit.pvalue    0.758

The substantive treatment of both functions (the meaning of each residual type, the formulas used, the inferential quantities in the summary table, and the special case of casewise residuals) is given in Section 10.8.

9.7 Fit measures: fitMeasures()

The function fitMeasures() (alias fitmeasures()) returns a named numeric vector of fit indices. With the default fit_measures = "all", lavaan returns the complete set; alternatively, one or more specific indices can be requested:

fitMeasures(fit, c("chisq", "df", "pvalue", "cfi", "tli", "rmsea", "srmr"))
 chisq     df pvalue    cfi    tli  rmsea   srmr 
24.361  8.000  0.002  0.975  0.953  0.082  0.047 

The full taxonomy of fit measures available in lavaan, with the exact formulas used by the implementation, is the topic of Section 10.2 (in particular, Section 10.3.1 for the CFI/TLI family, Section 10.4 for the RMSEA, and Section 10.5 for the SRMR family).

9.8 Hypothesis tests

9.8.1 Likelihood ratio test: anova() and lavTestLRT()

For nested models, the likelihood ratio test (LRT) compares two fitted objects:

HS_model.0 <- '
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  visual ~~ 0*textual
'
fit0 <- cfa(HS_model.0, data = HolzingerSwineford1939)
anova(fit, fit0)
Chi-Squared Difference Test

     Df    AIC    BIC  Chisq Chisq diff   RMSEA Df diff Pr(>Chisq)    
fit   8 5066.5 5114.7 24.361                                          
fit0  9 5100.1 5144.6 59.942     35.581 0.33895       1  2.447e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The anova() method dispatches to lavTestLRT(), which also accepts additional arguments (for example, method = "satorra.bentler.2010" for the Satorra–Bentler scaled difference test).

9.8.2 The lavTest() function

lavTest() recomputes the overall goodness-of-fit test statistic for a fitted model without re-estimating it; this is the convenient way to add a robust or residual-based test post hoc. See Section 8.5.13 for details.

9.8.3 Score test: lavTestScore()

The score test (Lagrange multiplier test) evaluates whether a parameter that is currently fixed (or constrained) could profitably be freed, without actually refitting the model. It is the multivariate counterpart of the modification index (Section 10.11), and it is the appropriate tool when the constraint to be tested is an equality constraint (a == b) rather than a fixed-to-constant parameter (Section 10.11.4):

model_con <- '
  visual  =~ x1 + b1*x2 + b2*x3
  textual =~ x4 + b3*x5 + x6
  b1 == b2
  b2 == b3
'
fit_con <- cfa(model_con, data = HolzingerSwineford1939)
lavTestScore(fit_con)
$test

total score test:

   test   X2 df p.value
1 score 8.65  2   0.013

$uni

univariate score tests:

  lhs op rhs    X2 df p.value
1  b1 ==  b2 5.761  1   0.016
2  b2 ==  b3 6.867  1   0.009

By default, both a univariate test (one statistic per restriction) and a multivariate test (all restrictions jointly) are returned. To test the second constraint only:

lavTestScore(fit_con, release = 2L, univariate = FALSE)
$test

total score test:

   test    X2 df p.value
1 score 6.867  1   0.009

The add argument allows arbitrary new parameters, specified in lavaan model syntax, to be tested for inclusion:

newpar <- '
  visual =~ x6
  textual =~ x3
'
lavTestScore(fit_con, add = newpar)
$test

total score test:

   test     X2 df p.value
1 score 10.199  2   0.006

$uni

univariate score tests:

          lhs op rhs    X2 df p.value
1  visual=~x6 ==   0 3.991  1   0.046
2 textual=~x3 ==   0 6.221  1   0.013

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

9.8.4 Wald test: lavTestWald()

lavTestWald() evaluates a linear or nonlinear hypothesis about the estimated parameters of the fitted model:

model_uncon <- '
  visual  =~ x1 + b1*x2 + b2*x3
  textual =~ x4 + b3*x5 + x6
'
fit_uncon <- cfa(model_uncon, data = HolzingerSwineford1939)
lavTestWald(fit_uncon, constraints = 'b1 == b2')
$stat
[1] 1.683023

$df
[1] 1

$p.value
[1] 0.1945233

$se
[1] "standard"
lavTestWald(fit_uncon, constraints = 'b1 == b2; b2^2 == 0.5*b3')
$stat
[1] 3.404811

$df
[1] 2

$p.value
[1] 0.1822446

$se
[1] "standard"

The Wald statistic is based on the variance–covariance matrix of the estimated parameters (as returned by vcov()). If robust (sandwich-type) standard errors were requested when fitting the model, the main statistic is therefore already the generalized (‘robust’) Wald test of Satorra (2000). In that case (or when a scaled test statistic was requested), the returned list additionally contains the standard (normal-theory), mean-scaled, and mean-and-variance adjusted versions of the statistic.

9.9 Modification indices: modindices()

modindices() (synonyms modificationIndices(), modificationindices()) returns, for every parameter that is currently fixed in the model, an estimate of the expected drop in the chi-square test statistic if that parameter were freed:

modindices(fit, sort = TRUE, maximum_number = 10)

Output columns include the modification index (mi), the expected parameter change (epc), and the standardized expected parameter change (sepc.lv, sepc.all, sepc.nox). When robust standard errors or a scaled test statistic were requested, a scaled (robust) version of the modification index is added in the mi.scaled column. With power = TRUE, columns for power statistics under a user-supplied effect size delta are added as well. The score-test interpretation of the modification index, the formulas used to compute the EPC and its standardized variants, and a detailed discussion of power = TRUE are given in Section 10.11.

9.10 Factor scores and casewise quantities

9.10.1 predict() and lavPredict()

predict() returns factor scores. Internally, it calls lavPredict() with default arguments; lavPredict() itself exposes many more options (Table 9.5):

Table 9.5: Selected arguments of lavPredict().
Argument Default Effect
type "lv" Return factor scores ("lv"), implied y values ("yhat"), or implied observed scores ("ov")
method "EBM" Empirical Bayes; alternatives: "regression", "Bartlett", "ML"
newdata NULL Compute scores for a new data set
se "none" Standard errors of factor scores
acov "none" Asymptotic covariance matrix of factor scores
fsm FALSE Return the factor score matrix as an attribute
mdist FALSE Add (squared) Mahalanobis distances of the factor scores (or casewise residuals) as an attribute
head(lavPredict(fit))
head(lavPredict(fit, method = "regression"))

Note that method = "Bartlett" also supports higher-order factor models (the scores for the higher-order factors are then computed from the collapsed measurement model), standard errors (se=) are available for categorical factor scores, and the Mahalanobis-distance diagnostics (mdist = TRUE) are generalized to ordered categorical data following Mansolf and Reise (2017).

A related function, lavPredictY(), does not compute factor scores but predicts the values of the observed y-variables from the values of the observed x-variables, using the model-implied joint distribution. Its companion lavResidualsY() returns the corresponding casewise residuals: the observed minus the predicted values of the y-variables.

9.10.2 lavScores()

lavScores() returns the matrix of casewise score vectors, that is, the contribution of each observation to the gradient of the objective function at the solution. The result is an N \times T matrix that is used internally by the Huber–White sandwich estimator (see se = "robust.huber.white") and by several diagnostic tools. Casewise scores are available for the ML, GLS, WLS, and ULS estimators, and for the pairwise maximum likelihood (PML) estimator. When the model contains equality constraints, the scores reflect them via a Lagrange-multiplier projection (so that the columns still sum to zero); inequality constraints (including automatically generated bounds) are left untouched, as they do not restrict the sampling variability of the estimator at an interior solution. For a two-level model (ML only), the scores are cluster-wise: the result has one row per cluster instead of one row per observation (see Section 16.8.2).

SC <- lavScores(fit)
dim(SC)
colSums(SC)   # should be (numerically) zero at the solution

9.11 Other standard methods

9.11.1 logLik(), AIC(), BIC()

logLik() returns the value of the log-likelihood at the fitted parameters in the standard form used by R, which carries the number of free parameters and the sample size along with the value. As a consequence, the generic methods AIC() and BIC() work directly:

logLik(fit)
'log Lik.' -2520.252 (df=13)
AIC(fit)
[1] 5066.503
BIC(fit)
[1] 5114.696

For multivariate normal data with complete cases, the log-likelihood matches the value returned by fitMeasures(fit, "logl"). The exact formulas used to compute AIC, BIC, and the sample-size adjusted BIC (SABIC) are given in Section 10.6.

9.11.2 nobs()

nobs() returns the (effective) sample size N. For multiple-group models, the result is the total sample size summed over groups; the group-specific sample sizes can be obtained with lavInspect(fit, "nobs").

9.11.3 update()

update() refits the model after modifying the call. The first argument is the original lavaan object; the second optional argument is a replacement model syntax; further named arguments override the corresponding arguments of the original call:

fit_mlm <- update(fit, estimator = "MLM")
fit_b   <- update(fit, model = HS_model.0)

When the evaluate argument is set to FALSE, the modified call is returned unevaluated, which is useful for inspection or scripting.

9.11.4 show()

When a lavaan object is typed at the console, the show() method prints a short description of the object (the estimator, the optimizer, the number of free parameters, and the sample size) together with the model test statistics, each with its degrees of freedom and p-value:

fit
lavaan 0.7-4 ended normally after 28 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        13

  Number of observations                           301

Model Test User Model:
                                                      
  Test statistic                                24.361
  Degrees of freedom                                 8
  P-value (Chi-square)                           0.002
                                                      
  Browne's residual (NT model-based) test             
  Test statistic                                24.488
  Degrees of freedom                                 8
  P-value (Chi-square)                           0.002

This is the same information that appears in the header block of summary().

9.12 lavInspect() and lavTech()

The function lavInspect() (with backward-compatible alias inspect()) is the most general function for accessing internal quantities of a fitted lavaan object in a human-readable form. It accepts the lavaan object as its first argument and a keyword what= that selects the quantity of interest. Almost any quantity that lavaan computes can be obtained this way, with row and column labels attached automatically.

lavTech() is a “technical” version of the same function: it returns the same quantities but with add_labels = FALSE, add_class = FALSE, and drop_list_single_group = FALSE (see Section 9.12.3). The result is therefore stripped of cosmetic information and is more convenient for further programmatic processing.

9.12.1 Common keywords

The full list of recognized keywords is long (well over a hundred, not counting aliases). Table 9.6 summarizes the most commonly used keywords, grouped by topic. The complete catalog (every keyword, its aliases, and what it returns, organized by theme) is given in appendix G (and on the manual page of the lavInspect() function).

Table 9.6: Selected what= keywords for lavInspect().
Keyword group Example keywords Returns
Model matrices "free", "est", "se", "start", "std", "est_unrotated" Model matrices with various entries
Single model matrices "mm_lambda", "mm_theta", "mm_delta" One specific model matrix per group (the bare names remain as aliases)
VCOV "vcov", "vcov_std_all", "vcov_def" Variance–covariance matrix of (free, standardized, defined) parameters
Sample statistics "sampstat", "cov_ov", "mean_ov", "wls_obs" Observed sample statistics
Model-implied "implied", "cov_lv", "mean_lv", "th", "wls_est" Model-implied summary statistics
Information "information", "information_expected", "information_observed", "h1_information" The (expected, observed, \mathsf{H}_1) information matrix
Delta method "delta", "delta_rownames", "gamma" The Jacobian (\boldsymbol{\Delta}) of the model-implied statistics, its row labels, and the asymptotic covariance matrix (\boldsymbol{\Gamma}) of the sample statistics
Data structure "nobs", "norig", "ntotal", "ngroups", "group", "cluster", "nlevels", "data", "case_idx", "coverage", "empty_idx" Data-related quantities
Multilevel "icc", "cluster_id", "cluster_size", "average_cluster_size" Clustering / multilevel information
Casewise diagnostics "mdist_fs", "mdist_resid", "mdist2_fs", "mdist2_resid" (Squared) Mahalanobis distances of the (Bartlett) factor scores or the casewise residuals (also for ordered categorical data)
Monte Carlo draws "monte_carlo" (alias "mc") The Monte Carlo draws of the model parameters used for the confidence intervals of defined parameters when se_def = "monte.carlo"
Optimization "converged", "iterations", "optim", "gradient" Optimizer information
Miscellaneous "version", "call", "options", "npar", "meanstructure", "categorical", "ordered", "parameterization", "fixed_x" Object metadata

Many keywords have multiple aliases (for example, "std", "std_all", "est_std", "standardized" all return the same information). The authoritative mapping is part of the inspection code (Section 9.13); appendix G.17 shows how to enumerate the keywords programmatically.

9.12.2 Some examples

The model matrices in their estimated form:

lavInspect(fit, "est")
$lambda
   visual textul
x1  1.000  0.000
x2  0.559  0.000
x3  0.708  0.000
x4  0.000  1.000
x5  0.000  1.111
x6  0.000  0.925

$theta
      x1    x2    x3    x4    x5    x6
x1 0.536                              
x2 0.000 1.125                        
x3 0.000 0.000 0.863                  
x4 0.000 0.000 0.000 0.369            
x5 0.000 0.000 0.000 0.000 0.449      
x6 0.000 0.000 0.000 0.000 0.000 0.356

$psi
        visual textul
visual   0.822       
textual  0.414  0.981

The free-parameter matrix (which gives, for each model matrix, the integer index of the free parameter at each position, or zero where the element is fixed):

lavInspect(fit, "free")
$lambda
   visual textul
x1      0      0
x2      1      0
x3      2      0
x4      0      0
x5      0      3
x6      0      4

$theta
   x1 x2 x3 x4 x5 x6
x1  5               
x2  0  6            
x3  0  0  7         
x4  0  0  0  8      
x5  0  0  0  0  9   
x6  0  0  0  0  0 10

$psi
        visual textul
visual      11       
textual     13     12

The model-implied summary statistics for this model:

lavInspect(fit, "implied")
$cov
      x1    x2    x3    x4    x5    x6
x1 1.358                              
x2 0.459 1.382                        
x3 0.582 0.325 1.275                  
x4 0.414 0.231 0.293 1.351            
x5 0.460 0.257 0.325 1.090 1.660      
x6 0.383 0.214 0.271 0.908 1.009 1.196

The observed sample statistics:

lavInspect(fit, "sampstat")
$cov
      x1    x2    x3    x4    x5    x6
x1 1.358                              
x2 0.407 1.382                        
x3 0.580 0.451 1.275                  
x4 0.505 0.209 0.208 1.351            
x5 0.441 0.211 0.112 1.098 1.660      
x6 0.455 0.248 0.244 0.896 1.015 1.196

The variance–covariance matrix of the parameter estimates and its standardized counterpart:

lavInspect(fit, "vcov")
lavInspect(fit, "vcov_std_all")

Three types of information matrix (the basis of the conventional and robust standard errors of Section 8.4):

lavInspect(fit, "information_expected")
lavInspect(fit, "information_observed")
lavInspect(fit, "information_first_order")

Data structure and optimizer status:

lavInspect(fit, "nobs")
[1] 301
lavInspect(fit, "ngroups")
[1] 1
lavInspect(fit, "converged")
[1] TRUE
lavInspect(fit, "iterations")
[1] 28

9.12.3 lavInspect() versus lavTech()

The difference between the two functions is best illustrated with an example. With lavInspect(), the result of "wls_obs" is a labeled vector carrying a lavaan-specific class that only affects how it is printed:

M1 <- lavInspect(fit, "wls_obs")
str(M1)
 'lavaan.vector' Named num [1:21] 1.358 0.407 0.58 0.505 0.441 ...
 - attr(*, "names")= chr [1:21] "x1~~x1" "x1~~x2" "x1~~x3" "x1~~x4" ...
M1
x1~~x1 x1~~x2 x1~~x3 x1~~x4 x1~~x5 x1~~x6 x2~~x2 x2~~x3 x2~~x4 x2~~x5 x2~~x6 
 1.358  0.407  0.580  0.505  0.441  0.455  1.382  0.451  0.209  0.211  0.248 
x3~~x3 x3~~x4 x3~~x5 x3~~x6 x4~~x4 x4~~x5 x4~~x6 x5~~x5 x5~~x6 x6~~x6 
 1.275  0.208  0.112  0.244  1.351  1.098  0.896  1.660  1.015  1.196 

The corresponding lavTech() call returns a plain numeric vector without labels or class wrappers, ready to be used in further computations:

M2 <- lavTech(fit, "wls_obs")
str(M2)
List of 1
 $ : num [1:21] 1.358 0.407 0.58 0.505 0.441 ...
M2
[[1]]
 [1] 1.3583698 0.4073713 0.5798993 0.5048350 0.4406155 0.4548081 1.3817839
 [8] 0.4510639 0.2089234 0.2110911 0.2475446 1.2748649 0.2081696 0.1122963
[15] 0.2441090 1.3506645 1.0977528 0.8955157 1.6597858 1.0145240 1.1963584

Note that lavTech() always returns a list of groups, even if there is only one group. This is useful when writing code that should work for both single-group and multiple-group models. To fine-tune the output, the following arguments are available for both lavInspect() and lavTech():

  • add_labels: if TRUE, variable names are added to the vectors and/or matrices.

  • add_class: if TRUE, vectors and (symmetric) matrices are given a lavaan-specific class whose only purpose is formatted printing (rounding to a fixed number of decimals, and showing only the lower triangle of a symmetric matrix); the numerical content is unchanged.

  • list_by_group: only used when the output consists of model matrices. If TRUE, the model matrices are nested within groups; if FALSE, a flattened list is returned containing all model matrices, with repeated names for multiple groups.

  • drop_list_single_group: if FALSE, the results are returned as a list, with one element per group (even if there is only a single group). If TRUE, the list is unwrapped when there is only a single group.

These four arguments default to TRUE under lavInspect() and to FALSE under lavTech(). Intermediate settings can be requested by passing the arguments explicitly:

lavTech(fit, "wls_obs", drop_list_single_group = TRUE, add_labels = TRUE)
   x1~~x1    x1~~x2    x1~~x3    x1~~x4    x1~~x5    x1~~x6    x2~~x2    x2~~x3 
1.3583698 0.4073713 0.5798993 0.5048350 0.4406155 0.4548081 1.3817839 0.4510639 
   x2~~x4    x2~~x5    x2~~x6    x3~~x3    x3~~x4    x3~~x5    x3~~x6    x4~~x4 
0.2089234 0.2110911 0.2475446 1.2748649 0.2081696 0.1122963 0.2441090 1.3506645 
   x4~~x5    x4~~x6    x5~~x5    x5~~x6    x6~~x6 
1.0977528 0.8955157 1.6597858 1.0145240 1.1963584 

9.13 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.

The lavaan object is a formal S4 object. Its components are stored in slots, which can be listed with slotNames():

slotNames(fit)
 [1] "version"     "call"        "timing"      "Options"     "ParTable"   
 [6] "pta"         "Data"        "SampleStats" "Model"       "Cache"      
[11] "Fit"         "boot"        "optim"       "loglik"      "implied"    
[16] "vcov"        "test"        "h1"          "baseline"    "internal"   
[21] "external"   

Table 9.7 describes the slots in the order in which they are filled during the fitting process. Some of them are themselves S4 objects with their own slots: Data is of class "lavData", SampleStats of class "lavSampleStats", and Model of class "lavModel". All formal class definitions are collected in a single file (00class.R), and the generic functions for the lavaan-specific methods are declared in 00generic.R.

Table 9.7: Slots of the lavaan object.
Slot Contents
version The lavaan version that created the object
call The matched call
timing Elapsed time of the main steps of the fitting process
Options The resolved options (the output of lavOptions(), after the defaults have been filled in)
ParTable The parameter table, as a list of columns
pta Parameter-table attributes: variable names per block, the number of groups and levels, …
Data The processed data ("lavData" object)
SampleStats The sample statistics ("lavSampleStats" object), including the \boldsymbol{\Gamma} and \mathbf{W} matrices when needed
Model The internal model representation ("lavModel" object): the model matrices, the free-parameter and constraint bookkeeping
Cache Precomputed quantities that speed up the objective function (currently used by the pairwise maximum likelihood estimator)
Fit Older container (class "Fit") duplicating the estimates, the value of the objective function, and the convergence status; kept for backward compatibility
boot Bootstrap draws, when se = "bootstrap" or test = "bollen.stine" was used
optim The results of the optimizer: parameter vector, convergence status, iteration count, gradient, …
loglik The log-likelihood and the quantities needed for AIC and BIC
implied The model-implied moments
vcov The variance–covariance matrix of the estimates, with the information matrices it was built from
test One list element per requested test statistic
h1 The \mathsf{H}_1 (unrestricted) model: implied moments and log-likelihood
baseline The parameter table and the test statistics of the fitted baseline model, for the incremental fit indices
internal Internal bookkeeping (used, among others, by lavTestLRT() and the SAM functions)
external A list for user-supplied objects, such as a custom h1.model

The slots are accessible with the @ operator (fit@ParTable, say), but nothing in the main text relies on this: every quantity used in this book is obtained through parTable(), lavInspect(), lavTech(), or one of the other accessors. Where version 0.7-4 offers no accessor, the book says so.

Several accessors return objects with a lavaan-specific S3 class whose only purpose is formatted printing. summary() returns an object of class "lavaan.summary", a list with (depending on the arguments) the elements header, optim, data, test, pe, fit, and a few more; the printer is registered as the print() method for that class. With add_class = TRUE, lavInspect() wraps vectors in class "lavaan.vector", matrices in class "lavaan.matrix", and symmetric matrices in class "lavaan.matrix.symmetric"; the corresponding print() methods round to nd decimals and, for symmetric matrices, show only the lower triangle. logLik() returns a standard "logLik" object, carrying the attributes df (the number of free parameters) and nobs, which the generic AIC() and BIC() methods use.

Table 9.8 maps the functions of this chapter to their source files.

Table 9.8: Source files behind the lavaan object and its methods.
Topic File(s)
S4 class definitions (lavaan, lavData, lavSampleStats, lavModel, …) 00class.R
S3/S4 generics 00generic.R
summary(): collecting the components lav_object_summary.R
printing methods (incl. the "lavaan.summary" printer and the "lavaan.vector"/"lavaan.matrix" printers) lav_print.R
lavInspect()/lavTech() keyword mapping lav_object_inspect.R