When fitting a model using the lavaan() function (or one of its wrappers), the data can be supplied either as raw data or as precomputed sample statistics, the latter either as separate arguments or bundled in a single lavMoments object. Raw data is the more flexible option: it enables lavaan to handle missing values, categorical variables, and the full range of estimation options. Sample statistics alone suffice in some situations (for example, when only summary statistics are available), with certain limitations.
This chapter describes how lavaan processes the input data, in either form, and organizes the result in three stages: the processed data and its metadata; the sample statistics computed from it, also in the presence of exogenous covariates, missing data, multilevel structures, or ordered categorical variables; and the estimates of the unrestricted (\mathsf{H}_1) model, the saturated benchmark against which model fit is evaluated. All three are kept inside the fitted lavaan object, and everything a user may need from them is reachable through the lavInspect() and lavTech() accessors.
5.1 Using the data argument to provide raw data
The most common way to provide data to lavaan is through the data argument, which accepts a raw data frame. This data frame should have one row per observation and one column per variable. It may contain more variables than are actually needed for the analysis; lavaan will automatically extract only those required by the specified model.
Ideally, the input should be an object of class data.frame, R’s standard format for tabular data. If another type (such as a tibble) is provided, lavaan will internally convert it to a standard data frame. In addition to the data itself, several optional arguments can be used to specify important structural features of the dataset:
group: Names the variable that defines groups in a multiple-group analysis.
cluster: Specifies the variable that defines clusters in multilevel data.
sampling_weights: Indicates the variable containing case-level (sampling) weights.
ordered: Identifies which variables should be treated as ordered categorical; if set to TRUE, all endogenous variables are treated as ordered.
std_ov: If TRUE, standardizes numeric variables. When fixed_x = FALSE, all variables are standardized; when fixed_x = TRUE, only the endogenous variables are standardized.
missing: Determines how missing data should be handled.
One of the first tasks lavaan performs after receiving the model syntax is to determine the names of the observed variables referenced in the model. It checks whether all these variables are present in the dataset and issues an error if any are missing. Only the required variables are extracted from the data and kept internally as a numeric matrix1.
Based on the model syntax, lavaan can also identify which observed variables are treated as exogenous, a distinction that is used in several of the later checks. In the case of a multilevel model, lavaan further determines the level (within or between) at which each observed variable is situated. These sets of names can be retrieved from a fitted object with lavNames(), for example lavNames(fit, "ov_x") for the exogenous covariates.
If the model includes exogenous covariates and fixed_x = TRUE or conditional_x = TRUE, lavaan keeps them apart from the other observed variables, since they are treated differently in the later computations (see Section 5.6.2 and Section 5.6.4).
5.1.1 The variable table
Next, lavaan inspects the input data by constructing a variable table in which each row corresponds to one observed variable used in the model. This table summarizes key metadata for each variable, including:
the index of the variable in the original dataset (idx)
the number of non-missing observations (nobs)
the variable type (type), such as numeric, ordered, or factor
the mean (mean) and variance (var) for numeric variables
the number of categories (nlev) for categorical variables
the labels of these categories (lnam)
This table can be generated by the public function varTable():
name idx nobs type exo user mean var nlev lnam
1 x1 7 301 numeric 0 0 4.936 1.363 0
2 x2 8 301 numeric 0 0 6.088 1.386 0
3 x3 9 301 numeric 0 0 2.250 1.279 0
4 x4 10 301 numeric 1 0 3.061 1.355 0
5 school 5 301 factor 0 0 NA NA 2 Grant-White|Pasteur
The primary purpose of the variable table is to facilitate error checking. For example, lavaan does not permit the use of unordered categorical variables (i.e., those of type factor) in the model. If such variables are detected, an error is raised, unless the variable is exogenous and binary (i.e., has exactly two levels). Unlike functions such as lm() in base R, lavaan does not automatically generate dummy variables for categorical predictors. If dummy coding is needed, the user must prepare these variables manually before passing the data to lavaan.
For ordered categorical variables (type ordered), lavaan checks that the variable is not exogenous, and that it has between 2 and 12 categories. For numeric variables, it checks that the variable is not constant (zero variance), and flags any variable whose variance exceeds a very large threshold (e.g., 1,000,000). Additionally, for non-exogenous variables, a warning is issued if the variance of one variable is at least 1,000 times greater than that of another, which may suggest poor scaling, a known cause of numerical instability during estimation.
Finally, for non-exogenous variables, a warning is also triggered if any pair of variables is found to be perfectly correlated.
5.1.2 Interaction terms among observed variables
If the model syntax contains two-way product or interaction terms (for example, x1:x2 or x2:x2), and both variables are observed, lavaan will automatically compute the corresponding product and add it to the internal data matrix. This is accomplished by directly multiplying the two observed variables, unless a variable with the same name (such as x1:x2) is already present in the dataset. Importantly, no centering is applied before constructing the product term. Users who wish to apply a specific transformation, such as mean-centering the variables prior to forming the product, are advised to compute the product manually and include it in the dataset. Once created, these product terms are treated as standard observed variables in the analysis.
5.1.3 Multiple groups
If a group variable is specified, lavaan first determines how many distinct groups are present in the dataset. It then creates a separate data matrix for each group. In most applications, there is only a single group. However, lavaan consistently supports multiple (independent) groups throughout, and the single-group case is treated as a special instance of the general multi-group structure. This is visible in the accessors: whenever there is more than one group, lavInspect(fit, "data") and most other data-related keywords return a list with one element per group.
In standard use, the observed variables are the same across all groups. However, if the model syntax uses the group-specific block operator (group:), then each group can define its own set of observed variables, which may overlap partially or not at all with those in other groups. This flexibility is the reason lavaan stores a separate data matrix per group, rather than maintaining a single combined matrix with an additional grouping variable, as in the original dataset.
5.1.4 Clustered data
If a cluster variable is provided, lavaan treats the data as clustered and stores additional information about the clustering structure. However, this does not automatically mean that a multilevel model will be estimated. That depends on whether a multilevel structure is explicitly defined in the model syntax. Conversely, if a multilevel structure is specified in the syntax, the data must include a cluster variable; otherwise, an error will be raised.
Typically, the cluster variable is a single column in the dataset, but multiple clustering variables can be supplied as a vector2.
To describe the clustering structure of the data, lavaan determines the following information (each item can be retrieved from a fitted object with lavInspect() and the keyword shown):
nclusters: The number of distinct clusters identified in the data, denoted by J.
cluster_size: A vector of length J indicating the number of observations within each cluster.
cluster_sizes: The unique cluster sizes that occur in the data. This vector will have length \leq J.
ncluster_size: The number of unique cluster sizes. If this number is 1, the clustering is considered balanced.
cluster_id: A vector of length J containing the IDs of the clusters.
cluster_idx: A vector of length N (where N is the total number of observations per group) that maps each observation to its corresponding cluster, numbered from 1 to J.
A warning is issued if the number of clusters J equals the number of observations N (within a group), or if the average cluster size is less than 1.5, as this typically suggests that most clusters contain only a single observation.
If a multilevel structure is specified, lavaan performs additional checks on the observed variables to ensure consistency with the declared level structure. If a variable is declared as a level-1 (within-cluster) variable but exhibits no variation within each cluster, a warning is issued, as this may suggest the variable is actually a level-2 (between-cluster) variable. Similarly, if a level-1 variable has zero variance in only some clusters, a warning is generated identifying the cluster IDs where this occurs. Conversely, if a variable declared as level-2 shows nonzero within-cluster variance in at least one cluster, a warning is given, as this could indicate the variable is more appropriately treated as a level-1 variable.
5.1.5 Long panel data: the panel argument
Repeated measures are often stored in long format, with one row per person and occasion, whereas a model for repeated measures is written for the wide variables, one per variable and per wave (x1, x2, …; Section 2.8). The panel argument names the id and the time variable of long data, as in panel = c(id = "pid", time = "wave"), and lavaan reshapes the data to the wide format (one row per id) before the analysis: the variable x at time 3 becomes x3 (an optional element sep puts a separator between the name and the time; sep = "_" gives x_3). The time variable must contain non-negative integers, and every id can have at most one row per time. Occasions without a row become missing values, so that unbalanced panels are handled by missing = "ml". Only the wide variables that the model uses are created, and a name in the model may also be zero-padded (x03). Variables that are constant within each id (time-invariant covariates, and the group, cluster and sampling_weights variables) are kept as a single variable, and a variable that changes over time must be referred to at a given time (using it without a time is an error, as is a name that is both a column of the data and a wide name). In the ordered and aux arguments, the name of a time-varying variable stands for all its wide variables. The rows of the wide data are the ids, in the order of their first appearance in the data, and the long and the wide data give identical fits, whatever the order of the rows. For efa(), the wide names must be listed in the ov_names argument, since the function has no model from which to derive them.
For a two-level model (with level: blocks in the syntax), the data are not reshaped: every row is an occasion, the id variable is the cluster variable, and the model can use lagged variables (y ~ y[t-1]), which lavaan adds to the data in this step. This case is described in the multilevel chapter (Section 16.14).
5.1.6 Missing data
If the dataset contains missing values and listwise deletion is requested, only the complete cases (that is, rows without any missing values on the observed variables used in the model) are retained. Their row indices are returned by lavInspect(fit, "case_idx"). The number of retained cases is reflected in the output of lavInspect(fit, "nobs"), while the original number of rows per group (before deletion) is given by lavInspect(fit, "norig"). The output of lavInspect(fit, "ntotal") reflects the total number of observations actually used in the analysis. In a single-group setting, this equals the single nobs value, but in a multi-group analysis it is the sum of the per-group nobs values.
If a method other than listwise deletion is requested for handling missing data (e.g., "ml" or "pairwise"), lavaan analyzes the data to identify all unique missing data patterns. This is done separately for each group, and, if a multilevel structure is specified, at each level. For every missing data pattern, lavaan records which variables have missing values and how often the pattern occurs in the dataset. Observations that are “empty” (i.e., have missing values on all relevant variables) are excluded from the analysis, and a warning is issued with the row indices of those empty cases.
In addition, lavaan computes the coverage for every pair of variables, defined as the proportion of non-empty observations for which both variables are observed. This coverage matrix can be inspected using lavInspect(fit, "coverage"). A warning is triggered if the coverage is below 0.1 for any pair of variables. A separate warning is issued if the coverage for a pair of variables is exactly zero, perhaps due to missing-by-design patterns. In this case, the corresponding covariance cannot be computed and will be set (somewhat arbitrarily) to zero. The missing data patterns themselves are returned by lavInspect(fit, "patterns"), the number of cases per pattern by lavInspect(fit, "patterns_freq"), and the row indices of the empty cases by lavInspect(fit, "empty_idx").
5.1.7 Ordered categorical data
Ordered categorical variables are internally represented as integer values, with the first category coded as 1, the second as 2, and so forth.
Similar to how missing data are handled, lavaan tracks distinct response patterns for ordered categorical variables and counts how often each pattern occurs in the dataset; lavInspect(fit, "response_patterns") returns the patterns, their frequencies, and the number of possible patterns that were not observed. For certain estimation methods, operating on these patterns rather than on individual observations can greatly improve computational efficiency, since the number of unique patterns is typically much smaller than the total number of observations.
5.1.8 Sampling weights
Case-level sampling weights are normalized before they are used, unless the option sampling_weights_normalization is set to "none". By default, this option is set to "group", which rescales the weights so that their sum within each group equals that group’s sample size (nobs).
If sampling_weights_normalization is set to "total", the weights are rescaled so that their overall sum equals the total sample size (ntotal). For a single group, both settings are identical; they only lead to different results in multiple-group analyses with cross-group equality constraints, where the default ("group") matches the behavior of Mplus.
A related option, sampling_weights_type, determines how the weights are interpreted when computing the asymptotic variance of the sample statistics (the Gamma matrix, see Section 5.6.2): as design weights ("design", the default) or as frequency weights ("frequency", as if each case were physically replicated w_i times).
The final normalized sampling weights are returned per group by lavInspect(fit, "sampling_weights"), in the order of lavInspect(fit, "case_idx").
In a two-level model, the sampling_weights= argument has a different meaning: it gives the weights of the level-1 units within their cluster, which are rescaled per cluster (the sampling_weights_scaling option), while the weights of the clusters are given by a second argument, sampling_weights_cluster=. This is discussed in Section 16.10.
5.2 Providing sample statistics
Instead of providing raw data, users can supply precomputed sample statistics directly through the sample_cov, sample_mean, and sample_nobs arguments. This approach is common in simulation studies, when privacy concerns prevent sharing raw data, or when the original data are no longer available. However, using sample statistics instead of raw data has some limitations: sampling weights and clustered (multilevel) data are not supported, nor is there any mechanism for handling missing values. Still, multiple-group analyses are possible, and support exists for ordered categorical variables as well as for the conditional_x = TRUE option.
Robust standard errors and test statistics that rely on the asymptotically distribution-free (ADF) estimate of the Gamma matrix (see Section 5.6.2) cannot be computed from summary statistics alone, unless the user supplies the Gamma matrix explicitly via the nacov argument. By contrast, robust variants that only require the normal-theory version of the Gamma matrix can be computed from the sample moments directly. For example, when estimator = "ULS" is combined with moments-based input, lavaan automatically computes the normal-theory Gamma matrix needed for its default standard errors (se = "robust.sem.nt"), and the same holds for the test = "browne.residual.nt" test statistic. In these cases, a moments-based fit reproduces the corresponding raw-data fit exactly.
The sample_cov argument is typically a single variance-covariance matrix for the observed variables. It is important that the rows and columns of this matrix are named so that lavaan can correctly identify which variable corresponds to each row and column. For multiple-group analyses, sample_cov can be a named list, with one variance-covariance matrix per group. lavaan uses the lower triangle of the matrix. If the upper triangle differs from it beyond numerical noise, typically a typing error in a matrix entered by hand, a warning reports the number of differing pairs and the largest difference; a matrix whose upper triangle is entirely zero or NA is taken to be intentionally lower-triangular and triggers no warning.
Note that if the estimator is maximum likelihood (ML) and the likelihood option is set to "normal" (the default), lavaan internally rescales each group’s sample covariance matrix by a factor of (N-1)/N. This adjustment occurs because the default cov() function in R calculates the unbiased covariance matrix, dividing by N-1, while normal-theory maximum likelihood estimation requires division by N. Since lavaan assumes the input covariance matrix uses the unbiased estimate, it rescales accordingly. To prevent this rescaling, set the argument sample_cov_rescale to FALSE.
The sample_mean argument is optional and only required if the model syntax includes means or intercepts, or if the meanstructure option is set to TRUE. It should contain a vector of sample means or, for multiple-group analyses, a list of mean vectors, one for each group.
Unlike sample_mean, the sample_nobs argument is mandatory because, without access to the raw data, there is no other way to determine the sample size for each group. Accurate sample sizes are essential for computing correct standard errors and test statistics. If the true sample size is unknown and only point estimates are needed, an arbitrary sample size can be provided, in combination with se = "none" and test = "none". For multiple-group analyses, sample sizes can be supplied as a vector or a list.
A correlation matrix is not a covariance matrix, and using one as input for a covariance-structure analysis is the hybrid that the chapter on correlation structures warns against (Section 12.4). When all the variances in sample_cov equal one and the correlation argument was not given, lavaan therefore prints a note that suggests correlation = TRUE for a correlation-structure analysis, or an explicit correlation = FALSE to proceed with the covariance-structure analysis and suppress the note. Raw data that were standardized beforehand (all continuous model variables have unit variance) trigger the same note.
5.2.1conditional_x = TRUE
When the data are continuous and conditional_x = TRUE is specified, the model focuses on the residual covariance matrix obtained after regressing out the exogenous covariates. Consequently, for a conditional analysis, the sample_cov argument should contain the residual covariance matrix, and the sample_mean vector should hold the intercepts (rather than the raw means) after adjusting for the covariates. Additionally, three extra components are required: (1) the sample covariance matrix of the exogenous covariates, (2) their sample mean vector, and (3) the regression coefficients from the regression of endogenous variables on the covariates.
To illustrate this process, consider a simple regression model that is first estimated using raw data with the option conditional_x = TRUE:
model <-'x1 ~ x2 + x3 + x4'fit <-sem(model, data = HolzingerSwineford1939, conditional_x =TRUE)parameterEstimates(fit, output ="text", ci =FALSE)
Note that the res.slopes, cov.x, and mean.x information is stored as attributes of the sample_cov object. The same model can then be re-estimated using these summary statistics:
lavaan 0.7-4 ended normally after 16 iterations
Estimator ML
Optimization method NLMINB
Number of model parameters 5
Number of observations 301
Model Test User Model:
Test statistic 0.000
Degrees of freedom 0
Browne's residual (NT model-based) test
Test statistic 0.000
Degrees of freedom 0
parameterEstimates(fit_bis, output ="text", ci =FALSE)
The results obtained from this second model are identical to those from the initial fit based on raw data.
5.2.2 Ordered categorical data
When some or all endogenous variables are ordered categorical, it is still possible, though somewhat cumbersome, to conduct the analysis using only summary statistics. In addition to the usual sample statistics (such as polychoric correlations and thresholds), two extra components must be provided: the weight matrix (argument wls_v), which is required for (weighted) least squares estimation, and the “Gamma” matrix (argument nacov), used to calculate (robust) standard errors and test statistics. The Gamma matrix is the topic of Section 5.6.2 later in this chapter; the weight matrix is discussed in the chapter on estimation (see Section 7.4).
For illustration, consider an example based on a binary version of the Holzinger and Swineford dataset. The model is first estimated using the raw data:
lavaan 0.7-4 ended normally after 35 iterations
Estimator DWLS
Optimization method NLMINB
Number of model parameters 21
Number of observations 301
Model Test User Model:
Standard Scaled
Test Statistic 30.918 38.427
Degrees of freedom 24 24
P-value (Unknown) NA 0.031
Scaling correction factor 0.869
Shift parameter 2.861
simple second-order correction
An equivalent analysis can be performed using summary statistics only:
lavaan 0.7-4 ended normally after 35 iterations
Estimator DWLS
Optimization method NLMINB
Number of model parameters 21
Number of observations 301
Model Test User Model:
Standard Scaled
Test Statistic 30.918 38.427
Degrees of freedom 24 24
P-value (Unknown) NA 0.031
Scaling correction factor 0.869
Shift parameter 2.861
simple second-order correction
The reader can confirm that the two fits are identical. Note that there was no need to specify sample_cov_rescale = FALSE because the default estimator, DWLS, does not rescale the sample covariance matrix. The th.idx vector indicates which thresholds correspond to each variable. In this example, each variable has only one threshold, so each index from one to nine appears just once in the vector. For ordered variables with more than two categories, multiple thresholds are required per variable, causing the corresponding index to appear multiple times in the th.idx vector, once for each threshold. This th.idx vector must be supplied as an attribute of the sample_th argument.
This extract-and-refit procedure does not need to be performed by hand: the next section describes how all of the above can be obtained as a single object.
5.3 Providing a lavMoments object
The previous section showed that a moments-only analysis needs more than a covariance matrix: depending on the setting, also a mean vector, a threshold vector with its th.idx attribute, the wls_v and nacov matrices, and a set of options that must match the ones used to compute the statistics (conditional_x, sample_cov_rescale, and so on). Collecting all of these by hand is tedious and error-prone. lavaan therefore offers a container for them: an object of class lavMoments, which is a plain list of summary statistics whose components are named after the corresponding arguments of the fitting functions (sample_cov, sample_nobs, sample_mean, sample_th, wls_v, nacov), plus a lav_options component with the options a refit must use. Such an object can be passed directly as the data= argument of lavaan(), cfa(), or sem().
The usual way to create one is the lavH1() function, which computes the unrestricted (\mathsf{H}_1) summary statistics of a data set (the function is described in Section 5.7.4), with output = "lavMoments". A model syntax may be given as the first argument; it is used only to determine the variables involved, their roles, and the data-related options. The object has a print method that summarizes its contents:
lavaan summary statistics (class 'lavMoments')
Number of groups 1
Number of observations 301
Number of variables 9
Components sample_cov
Pass this object as the data= argument of lavaan()/cfa()/sem()
to (re)fit a model from these summary statistics.
Passing the object as the data argument reproduces the raw-data fit:
fit_raw <-cfa(HS_model, data = HolzingerSwineford1939)fit_mom <-cfa(HS_model, data = moments)c(fitMeasures(fit_raw, "chisq"), fitMeasures(fit_mom, "chisq"))
chisq chisq
85.30552 85.30552
Internally, the fitting function copies the components to the corresponding arguments (sample_cov = moments$sample_cov, and so on) and adds the stored options to the call, unless the user supplies the same option explicitly; an argument given in the call takes precedence over the stored value. Because the object is an ordinary list, its components can be inspected or modified in the usual way, and it can be saved with saveRDS() and shared in place of the raw data.
For multiple groups (group=), the sample_cov, sample_mean, and sample_th components are lists with one element per group, and sample_nobs is a vector; the group labels are stored in lav_options. With conditional_x = TRUE, the residual slopes and the moments of the exogenous covariates are attached as attributes of sample_cov, following the convention of the sample_cov argument described in Section 5.2. Two-level data are not supported: the summary statistics of a multilevel model cannot be packaged in this form.
The categorical example of the previous section now takes two lines. For ordered data, lavH1() includes the wls_v and nacov matrices by default, so that the refit reproduces the estimates, standard errors, and test statistics exactly:
moments_bin <-lavH1(HS_model, data = HSbinary, ordered =TRUE,output ="lavMoments")moments_bin
lavaan summary statistics (class 'lavMoments')
Number of groups 1
Number of observations 301
Number of variables 9
Ordered (categorical) variables yes (9)
Components sample_cov sample_mean sample_th wls_v nacov
Pass this object as the data= argument of lavaan()/cfa()/sem()
to (re)fit a model from these summary statistics.
fit_bin <-cfa(HS_model, data = moments_bin)c(fitMeasures(fit, "chisq_scaled"), fitMeasures(fit_bin, "chisq_scaled"))
chisq.scaled chisq.scaled
38.42706 38.42706
For continuous data, wls_v and nacov are not included unless requested (wls_v = TRUE, gamma = TRUE). The nacov matrix is what the robust MLM family needs, so a raw-data fit with estimator = "MLM" can be reproduced provided that the Gamma matrix was requested when the object was created, and that the estimator is passed to the refit (the estimator itself is not stored in the object):
moments_mlm <-lavH1(HS_model, data = HolzingerSwineford1939,estimator ="MLM", gamma =TRUE,output ="lavMoments")fit_mlm <-cfa(HS_model, data = HolzingerSwineford1939,estimator ="MLM")fit_mlm_mom <-cfa(HS_model, data = moments_mlm, estimator ="MLM")c(fitMeasures(fit_mlm, "chisq_scaled"),fitMeasures(fit_mlm_mom, "chisq_scaled"))
chisq.scaled chisq.scaled
80.87178 80.87178
For estimators whose weight matrix is estimator-specific (the ULS family, or the ADF weight matrix of continuous WLS), the same estimator should be given to lavH1() and to the refit, so that the matching wls_v matrix is stored. Incomplete continuous data are covered by two-stage estimation: with missing = "two.stage" (or "robust.two.stage"), lavH1() returns the EM estimates of the saturated moments together with the stage-1 nacov matrix and the options of the two-stage procedure, so that a moments-only refit gives the same estimates, standard errors, and scaled test statistic as the raw-data analysis.
What cannot be reproduced from summary statistics are the analyses whose standard errors or test statistic depend on the individual cases: the Huber-White sandwich of MLR, the first-order information of MLF, cluster-robust standard errors, the bootstrap, pairwise maximum likelihood, and direct full-information maximum likelihood for incomplete data (missing = "ml"). An overview of which analyses need the raw data is given in Section 7.9.
Finally, lavH1() is not the only source of such objects. Any function that produces summary statistics can return them in this form; the poolSat() function in the lavaan.mi package, for example, returns the pooled summary statistics after multiple imputation as a lavMoments object, so that a model can be fitted to the pooled moments with a single call.
5.4 Providing no data at all
In certain situations, it may be useful to call the lavaan() function (or one of its wrappers) without providing any data. In this case, lavaan will still parse the model syntax, generate the parameter table and model matrices, and perform the usual internal setup. Although no model fitting takes place, a fully functional lavaan object is created. This object can be inspected using the parameter table or extractor functions such as lavInspect(), which can be used, for example, to examine the variance–covariance matrix implied by the model and the parameter values specified in the syntax.
5.5 Inspecting the processed data
Regardless of whether data are provided as raw data or as sample statistics, the processed data and its metadata are kept inside the fitted lavaan object. Users and package developers should not rely on the internal layout of this information, which may change at any release. Instead, the extractor functions lavInspect() or lavTech() should be used to retrieve the data itself or other relevant information, such as the number of groups, clusters, or observations (per group or cluster). For example:
For a complete overview, see the “Information about the data” section in the manual page of the lavInspect() function, or appendix G.2 and G.3. Many of these keywords return a list with one element per group when there are several groups, as in this example.
A short description of the data also appears in the header of the summary() output (and in the output of print(fit)): the sample size per group, the number of missing data patterns (if any), the number of clusters (if the data are clustered), and the name of the sampling weights variable (if used).
5.6 Sample statistics
The processed data carries detailed information about the structure of the data, such as the number of groups, clusters, and missing data patterns. The next step in processing is to compute summary statistics for the data. These statistics, such as the sample covariance matrix and the sample mean vector, are crucial during model estimation. They also help detect potential issues with the data, for example, if the sample covariance matrix is not positive definite, which may cause the estimation process to stop early.
The computed sample statistics are kept inside the fitted object. The accessor lavInspect(fit, "sampstat") returns the main ones (means, covariances, thresholds, or their residual counterparts), and the keywords "wls_obs", "wls_v", and "gamma" return the derived quantities introduced below: the vector of nonredundant sample statistics, the weight matrix, and the Gamma matrix.
In some straightforward cases, such as complete data with all continuous variables, calculating the sample covariance matrix is simple, and typically amounts to a call of R’s cov() function (possibly with a rescaling factor of (N-1)/N if using normal theory maximum likelihood). However, in more complex situations, the computations become more involved. For example:
When data contain missing values and the missing option is set to "ml" (or its alias "fiml", for full information maximum likelihood), estimating the sample covariance matrix and mean vector requires iterative algorithms, usually based on the Expectation-Maximization (EM) algorithm.
When variables are ordered categorical, tetrachoric or polychoric correlations must be computed, along with a weight matrix used for (diagonally) weighted least squares estimation.
The computations involved are described elsewhere in the book: the EM algorithm for the saturated moments of incomplete continuous data in appendix D.9.7, its two-level counterpart in Section 16.6.2, and the stage-wise estimation of thresholds, polychoric correlations, and their asymptotic covariance matrix in Section 14.4.1 to Section 14.4.3. This section provides only an overview of the summary statistics that are produced, depending on the characteristics of the data and user-specified options such as the estimator and the value of the conditional_x argument.
5.6.1 Data are complete and continuous
Consider the standard scenario in which all variables are continuous and no missing values are present. Default settings are assumed, specifically estimator = "ML" and conditional_x = FALSE. Under these conditions, the following summary statistics are computed:
the sample covariance matrix of all observed variables (\mathbf{S}), returned by lavInspect(fit, "sampstat") as the element cov (its diagonal alone by lavInspect(fit, "var"));
the sample mean vector (\bar{\mathbf{y}}), returned as the element mean when a mean structure is specified;
the inverse of the sample covariance matrix (\mathbf{S}^{-1}) and the natural logarithm of its determinant (\text{ln}|\mathbf{S}|), which are needed repeatedly during estimation and are therefore computed once; they are returned by lavInspect(fit, "icov") and lavInspect(fit, "cov_log_det");
a vector containing the nonredundant observed sample statistics, returned by lavInspect(fit, "wls_obs"). By default, this includes the lower-triangular elements of the covariance matrix, \text{vech}(\mathbf{S}). If meanstructure = TRUE, the sample mean vector is prepended, yielding \mathbf{s}=
(\bar{\mathbf{y}}, \text{vech}(\mathbf{S})).
If estimator = "ML" and likelihood = "normal" (the default), then the sample covariance matrix is rescaled, meaning that all its elements are divided by N (the total number of observations) instead of N - 1. This aligns with the requirements of normal-theory maximum likelihood estimation, which assumes that the sample covariance matrix is computed using a divisor of N. For all other estimators, or if likelihood = "wishart", the unbiased sample covariance matrix is used, where the elements are divided by N - 1, as is standard in many statistical applications.
By default, the ridge option is set to FALSE. If it is set to TRUE, a small constant (typically 0.00001, though adjustable via the ridge_constant option) is added to the diagonal elements of \mathbf{S} before computing the inverse. This “ridge regularization” can be helpful in cases where the covariance matrix is nearly singular. This may occur, for example, when exogenous dummy variables are redundant by design.
In scenarios where the number of observations is less than the number of variables, or where numerical issues are expected, users may wish to bypass the computation of the inverse covariance matrix (\mathbf{S}^{-1}) and its determinant (|\mathbf{S}|). This can be done by setting the option sample_icov = FALSE.
5.6.2 The Gamma matrix
If maximum likelihood estimation is used in combination with robust standard errors (se = "robust.sem") or robust test statistics (e.g., test = "satorra.bentler"), lavaan needs to compute the so-called Gamma matrix, denoted by \boldsymbol{\Gamma}.
The \boldsymbol{\Gamma} matrix represents the sampling variability of the sample statistics. Intuitively, consider repeatedly drawing random samples of the same size from a population and computing the sample covariance matrix (\mathbf{S}) for each sample. From each covariance matrix, the nonredundant elements are extracted and stored in a vector \mathbf{s}=
\text{vech}(\mathbf{S}), which is then placed in the first row of a conceptual table.
A second sample produces another covariance matrix, from which \mathbf{s} is again extracted and placed in the second row of the table. Repeating this process an infinite number of times yields a table where each row corresponds to the sample statistics derived from one sample.
The variance-covariance matrix of the columns of this table, multiplied by the sample size N, gives the Gamma matrix. Formally,
where \text{ACOV}(\mathbf{s}) is the asymptotic covariance matrix of the vector of sample statistics \mathbf{s}. In other words, \boldsymbol{\Gamma} represents the scaled sampling variability of \mathbf{s}. In lavaan, if \boldsymbol{\Gamma} is computed, it is kept with the sample statistics and returned by lavInspect(fit, "gamma").
When the data are continuous and a mean structure is included, the vector of sample statistics is given by:
Here, the 1-subscript corresponds to the elements of the sample mean vector \bar{\mathbf{y}}, and the 2-subscript corresponds to the elements of the vectorized lower triangle of the sample covariance matrix, \text{vech}(\mathbf{S}).
Assuming multivariate normality, a consistent estimate of \boldsymbol{\Gamma} is given by the so-called normal theory (NT) estimator:
\mathbf{D}^{+} denotes the generalized inverse of the duplication matrix \mathbf{D},
\otimes is the Kronecker product,
the off-diagonal blocks are zero because under normality, the sample mean and sample covariance matrix are asymptotically independent.
If the assumption of multivariate normality is not desired, an alternative is to use a consistent, although not unbiased, asymptotically distribution-free estimator of the \boldsymbol{\Gamma} matrix:
That is, for each observation i, the raw values of the observed variables \mathbf{y}_i are stacked together with the vectorized lower triangle of the outer product of the mean-centered data.
This version of \hat{\boldsymbol{\Gamma}} is referred to as the ADF estimator, where ADF stands for Asymptotically Distribution Free. It can be used to compute robust standard errors and test statistics without relying on distributional assumptions, but it has a disadvantage: a large sample size is typically required to obtain a stable and reliable estimate.
To illustrate how the \boldsymbol{\Gamma} matrix can be computed from raw data, a simple function is provided below. This function takes a raw data matrix Y as input and computes a basic (ADF) estimate of \boldsymbol{\Gamma}:
compute_gamma <-function(Y, meanstructure =FALSE) { N <-nrow(Y); P <-ncol(Y) Yc <-t(t(Y) -colMeans(Y)) idx1 <-lav_mat_vech_col_idx(P) idx2 <-lav_mat_vech_row_idx(P)if (meanstructure) { Z <-cbind(Y, Yc[, idx1, drop =FALSE] * Yc[, idx2, drop =FALSE]) } else { Z <- (Yc[, idx1, drop =FALSE] * Yc[, idx2, drop =FALSE]) } Zc <-t(t(Z) -colMeans(Z)) Gamma <-crossprod(Zc)/N Gamma}
This function is provided for illustration purposes only. lavaan’s own implementation (mapped in the implementation notes at the end of this chapter) supports several additional features, such as:
Proper handling of exogenous covariates
Support for clustered data (if no multilevel analysis is used)
Support for group structures and sampling weights
Computation of an unbiased estimate of Gamma.
Users can request the unbiased version of Gamma (Browne, 1984) by setting the argument gamma_unbiased = TRUE.
For two-level data, a separate construction is used: the Gamma matrix is obtained as a cluster-based sandwich estimate, evaluated at the sample statistics of the unrestricted (\mathsf{H}_1) model. This two-level Gamma matrix also supports fixed_x = TRUE (the rows and columns corresponding to the moments of the exogenous covariates are set to zero, at each level) and missing data handled by missing = "ml".
The settings that determine which version of the Gamma matrix is used for a given analysis (and whether it is computed at all) are collected in a single place, which is consulted both when the model is fitted and when the Gamma matrix is requested afterwards, for example via lavInspect(fit, "gamma"). As a result, the Gamma matrix can be (re)computed after fitting for virtually all data types (continuous, categorical, missing data, two-level data), even if it was not needed (and therefore not stored) when the model was fitted. Table 5.1 lists, for each data setting, which estimate is used and where its definition can be found. Note that with missing = "ml", no Gamma matrix is computed when the model is fitted; the model-based incomplete-data variants of Section 8.3 are computed on request.
Table 5.1: Which estimate of \boldsymbol{\Gamma} is computed in which setting.
Setting
Estimate of \boldsymbol{\Gamma}
Where defined
complete continuous data, single level; ML or GLS with a robust se= or test=
If the estimator is set to "WLS", the inverse of the \boldsymbol{\Gamma} matrix is also computed. This inverse serves as the fixed weight matrix in the weighted least squares estimation procedure and is returned by lavInspect(fit, "wls_v"). The "DWLS" and "ULS" estimators use only the diagonal of this matrix, which lavInspect(fit, "wls_vd") returns as a vector.
If the estimator is set to "GLS", the weight matrix is constructed using the following block matrix structure:
This matrix corresponds to the inverse of the normal-theory Gamma matrix, \Gamma^{\mathrm{NT}}, and can be interpreted as the unit information matrix of the unrestricted (\mathsf{H}_1) model under the assumption of multivariate normality.
If no meanstructure is specified (i.e., meanstructure = FALSE), the first block row and column, corresponding to the means, are removed. In that case, only the lower-right block, which corresponds to the covariance structure, is retained.
If the model contains exogenous observed covariates, and the option fixed_x has been set to TRUE (the default), lavaan does not distinguish between endogenous and exogenous variables when computing most sample statistics. But the following two additional statistics are computed for convenience (e.g., for computing starting values):
mean.x: The sample means of the exogenous covariates
cov.x: The sample covariance matrix of the exogenous covariates only.
The only major exception concerns the Gamma matrix (and, as a result, the weight matrix), which must be adapted to reflect the assumption that the covariates are treated as fixed rather than random. This implies that the values of the covariates are assumed not to change from sample to sample, and this needs to be reflected in the computation of the Gamma matrix. It is a subtle but important point that has not received much attention in the SEM literature.
To illustrate, consider a regression model with two predictors. The model is first estimated with fixed_x = FALSE, and the Gamma matrix is requested:
fit_random <-sem('x1 ~ x2 + x3', data = HolzingerSwineford1939,fixed_x =FALSE, se ="robust.sem", meanstructure =TRUE)lavInspect(fit_random, "gamma")
Because the mean structure is included, the first three rows and columns correspond to the mean component of the normal Gamma matrix. In this case, the Gamma matrix is fully populated, since all three variables are treated as random, and their variances and covariances therefore fluctuate across samples.
Next, the same model is fitted with fixed_x = TRUE, and the Gamma matrix is requested:
fit_fixedx <-sem('x1 ~ x2 + x3', data = HolzingerSwineford1939,fixed_x =TRUE, se ="robust.sem", meanstructure =TRUE)lavInspect(fit_fixedx, "gamma")
In this case, the rows and columns corresponding to the exogenous covariates are all zero, as expected, because the values of the fixed variables (here, x2 and x3) do not vary across samples. Importantly, the remaining entries are smaller than the corresponding values in the fixed_x = FALSE case. Thus, the change is not limited to setting certain rows and columns to zero. The entire matrix is modified.
Since the computation of Gamma in the presence of fixed covariates is non-trivial, the procedure is outlined briefly here. Starting with the normal-based version of Gamma, denoted \boldsymbol{\Gamma}^{\mathrm{NT}}, one possible approach is to begin with the unrestricted information matrix:
Next, the influence of the exogenous covariates is “masked” by setting to zero all rows and columns corresponding to their variances and covariances. The inverse of this masked matrix is then obtained by excluding the rows and columns that were set to zero: the nonzero submatrix is extracted, inverted, and subsequently reinserted into the full matrix. This procedure produces the correct estimate for \boldsymbol{\Gamma}^{\mathrm{NT}}. The following code block illustrates these steps:
# sample covariance matrixS <-lavInspect(fit_random, "sampstat")$covS_inv <-solve(S)# mean part of the information matrix:I_un_mean <- S_inv# mask the rows/columns that correspond to the exogenous covariatesx_idx <-c(2,3)I_un_mean[x_idx, ] <-0I_un_mean[, x_idx] <-0# cov part of the information matrix:I_un_cov <-0.5*lav_mat_dup_pre_post(S_inv %x% S_inv)# mask the rows/columns that correspond to the exogenous covariatespstar_x <-which(lav_mat_vech_row_idx(nrow(S)) %in% x_idx &lav_mat_vech_col_idx(nrow(S)) %in% x_idx)I_un_cov[pstar_x, ] <-0I_un_cov[, pstar_x] <-0# combine masked information matrixI_un_masked <-lav_mat_bdiag(I_un_mean, I_un_cov)# invert the nonzero submatrix and reinsert it to get normal Gammakeep <-which(diag(I_un_masked) !=0)Gamma_NT <-matrix(0, nrow(I_un_masked), ncol(I_un_masked))Gamma_NT[keep, keep] <-solve(I_un_masked[keep, keep])round(Gamma_NT, 3)
Here, \mathcal{I}_{un} denotes the expected information matrix of the unrestricted (\mathsf{H}_1) model, and \mathcal{J}_{un} denotes the first-order information matrix of the unrestricted (\mathsf{H}_1) model. As before, it is necessary to mask the influence of the exogenous covariates. For the expected information matrix, this adjustment has already been made, allowing the use of Gamma_NT, which corresponds to the inverse of I_un_masked. The first-order information matrix of the unrestricted model, J_un, is obtained with lavTech() from the fit in which all variables are treated as random (fit_random, fitted with fixed_x = FALSE). The rows and columns corresponding to the exogenous covariates are then masked once more. Finally, the triple product of these masked information matrices is computed. The following code block illustrates these steps:
J_un <-lavTech(fit_random, "h1_information_first_order")[[1]]# mask exogenous rows and columnsmask_idx <-c(x_idx, nrow(S) + pstar_x)J_un_masked <- J_unJ_un_masked[mask_idx, ] <-0J_un_masked[, mask_idx] <-0# compute ADF version of GammaGamma_ADF <- Gamma_NT %*% J_un_masked %*% Gamma_NTround(Gamma_ADF, 3)
The reader can verify that this corresponds to the output of lavInspect(fit_fixedx, "gamma").
The identity above also reflects the two computational approaches that lavaan uses internally to obtain the (ADF) Gamma matrix. For complete, single-level data, the direct approach is used: the crossproduct of the casewise moment contributions, as illustrated by the compute_gamma() function shown earlier. The sandwich approach (\mathcal{I}_{un}^{-1} \mathcal{J}_{un} \mathcal{I}_{un}^{-1}) is used whenever the casewise contributions are not simple i.i.d. moment vectors: with sampling weights, with missing data, and with two-level data. For complete single-level data, both approaches give identical results (up to machine precision), but the direct approach is faster.
When the option conditional_x is set to TRUE, the situation changes fundamentally. Instead of modeling the joint covariance matrix of both endogenous and exogenous variables, the focus shifts to modeling the residual covariance matrix of the endogenous variables only, after the effects of the exogenous covariates have been regressed out. Consequently, besides the “joint” sample statistics (the covariance matrix and mean vector of all variables, with their derived quantities "var", "icov", and "cov_log_det") and the moments of the exogenous covariates (mean.x and cov.x), the following “residual” sample statistics are computed as well. The first four are returned by lavInspect(fit, "sampstat"); the last three have their own keywords.
res.cov: The residual sample covariance matrix of the endogenous variables, after regressing out the exogenous covariates (\mathbf{S}_{y|x})
res.slopes: The regression coefficients from the multivariate regression of the endogenous variables on the exogenous covariates
res.int: The intercepts from the multivariate regression of the endogenous variables on the exogenous covariates
cov.x and mean.x: The sample covariance matrix and the sample means of the exogenous covariates
"res_var": The residual variances of the endogenous variables (the diagonal elements of \mathbf{S}_{y|x})
"res_icov": The inverse of the residual sample covariance matrix (\mathbf{S}_{y|x}^{-1})
"res_cov_log_det": The natural logarithm of the determinant of the residual sample covariance matrix (\text{ln}|\mathbf{S}_{y|x}|).
If res.int and res.slopes are combined columnwise, the result is the matrix of regression coefficients, \mathbf{B}_{yx}, representing the regression of the endogenous variables (y) on the covariates (x). The residual sample statistics are then defined as a vector consisting of the vectorized transpose of \mathbf{B}_{yx}, concatenated with the half-vectorization of the residual covariance matrix \mathbf{S}_{y|x}:
This vector is returned by lavInspect(fit, "wls_obs"). The sampling variability of these residual sample statistics is represented by the residual Gamma matrix. For instance, after fitting a model with conditional_x = TRUE, the Gamma matrix can be extracted as follows:
fit_cond <-sem('x1 ~ x2 + x3', data = HolzingerSwineford1939,conditional_x =TRUE, se ="robust.sem")lavInspect(fit_cond, "gamma")
The weight matrix, if required, is the inverse of this Gamma matrix. In this setting, the elements returned by lavInspect(fit, "sampstat") carry the prefix res. (res.cov, res.int, res.slopes) and are accompanied by the moments of the covariates (cov.x, mean.x); the keywords "wls_obs", "wls_v", and "gamma" are unchanged.
The computation of both the normal and ADF versions of the Gamma matrix is relatively straightforward and considerably simpler than in the unconditional case when fixed_x = TRUE. For the normal case, Gamma can be partitioned into a regression component and a residual covariance component:
In this context, \mathbf{X} represents the matrix of all exogenous covariates, including a constant term for the intercept. The ADF version of Gamma is computed using a similar logic and parallels the approach used in the unconditional case. The following code block demonstrates how Gamma can be computed in the conditional case. This function takes two arguments as input: the Y matrix, which contains the endogenous variables only, and the X matrix, which contains the exogenous covariates along with a constant column for the intercept:
compute_gamma_cond <-function(Y, X) { N <-nrow(Y); Q <-ncol(X) fit_lm <-lm(Y ~ X) res <-as.matrix(resid(fit_lm)); P <-ncol(res) XtX_inv <-solve(crossprod(X)) Xi <- (X %*% XtX_inv) * N; x_idx <-rep(seq_len(Q), times = P) r_idx <-rep(seq_len(P), each = Q) idx1 <-lav_mat_vech_col_idx(P) idx2 <-lav_mat_vech_row_idx(P) Z <-cbind(Xi[, x_idx, drop =FALSE] * res[, r_idx, drop =FALSE], res[, idx1, drop =FALSE] * res[, idx2, drop =FALSE]) Zc <-t(t(Z) -colMeans(Z)) Gamma <-crossprod(Zc)/N Gamma}
The main distinction between this function and the unconditional version concerns the computation of Z. Instead of relying on the centered variables (Yc), the residuals (res) are used, and the original variables (Y) are replaced by the product of \mathbf{X} and N
(\mathbf{X^{\prime}X})^{-1} (Xi). lavaan’s own implementation (see the implementation notes at the end of this chapter) covers the general case.
To verify the correctness of the function, the Gamma computation is replicated for the regression example:
yx <-lavInspect(fit_cond, "data") # both y and x columnsY <- yx[, lavNames(fit_cond, "ov_nox"), drop =FALSE]X <-cbind(1, yx[, lavNames(fit_cond, "ov_x"), drop =FALSE])Gamma_cond <-compute_gamma_cond(Y = Y, X = X)round(Gamma_cond, 3)
This output coincides with the result obtained from lavInspect(fit_cond, "gamma").
5.6.5 Correlation structures
When a correlation structure is fitted (correlation = TRUE; see the parameter table chapter, Chapter 3, for the model side, and Section 12.5 for the estimation side), the set of sample statistics changes: the variances of the standardized variables are no longer statistics at all (by construction, they equal one in every sample), and their rows and columns must be removed from the moment vector. What remains are the sample correlations (plus, in the partial case discussed below, the variances of any variables that keep their original metric, and the appropriately rescaled means when a mean structure is included). The \boldsymbol{\Gamma} matrix must describe the sampling variability of this vector, and that is not the same as the sampling variability of the covariances.
The link between the two is the delta method. Each sample correlation is a smooth function of the sample covariances,
where \boldsymbol{\Gamma} is the ordinary Gamma matrix of the raw moments developed in the preceding sections. The Jacobian has a simple, sparse structure: with d_p = \sqrt{s_{pp}}, the row of r_{pp'} contains
and, when a mean structure is present, the row of a standardized mean carries the factor 1/d_p. The two variance derivatives are the essential part, and they explain why the standard errors must be adjusted at all when we standardize. A sample correlation inherits sampling variability from three sources: the covariance in its numerator, and the two sample variances used to standardize it. Ignoring the variance terms (treating r_{pp'} as if it were just a rescaled s_{pp'}) misstates its variability, and every standard error computed from it inherits the error. The resulting normal-theory expression for \boldsymbol{\Gamma}_R goes back to Neudecker and Wesselman (1990).
Note that Equation 5.1 does not depend on how \boldsymbol{\Gamma} was obtained: applied to the normal-theory \boldsymbol{\Gamma}^{\mathrm{NT}} it yields the normal-theory Gamma of the correlations (the inverse of which is the GLS weight matrix for correlation structures), and applied to the ADF estimator \hat{\boldsymbol{\Gamma}} it yields the distribution-free version used by WLS. The fixed_x = TRUE treatment of the earlier sections composes with it as well: the zeroing of the covariate rows happens in the raw \boldsymbol{\Gamma}, before the transformation.
The correlation argument may also name a subset of the observed variables; only those are standardized, while the others keep their original metric. The same Jacobian covers this case with three kinds of rows. The retained variance of a non-standardized variable gets a plain identity row (\partial s_{pp}/\partial s_{pp} = 1). A correlation between two standardized variables has the three derivatives given above. The mixed moment s_{pp'}/d_p between a standardized variable p and a non-standardized variable p' has only two nonzero entries: 1/d_p with respect to s_{pp'}, and -\tfrac{1}{2}\, s_{pp'}/(d_p\,
s_{pp}) with respect to s_{pp}. The variance s_{p'p'} of the non-standardized variable does not enter this moment, so its entry is zero. A single implementation covers the full and the partial case alike; it is mapped in the implementation notes at the end of this chapter.
Correlation structures also compose with conditional_x = TRUE: the exogenous covariates are standardized along with the outcomes, the moment vector takes the usual conditional layout in the standardized metric, and the unit-variance constraint applies to the marginal (joint) outcome variances, so that the residual diagonal becomes 1 - R^2. The delta-method Gamma of Equation 5.1 extends to this case as well, and a partial structure may standardize only a subset of the outcomes and/or covariates.
5.6.6 Missing data
If the dataset contains missing values, the treatment depends on the value of the missing option. When missing = "listwise" (the default), all cases with at least one missing value are discarded. The remaining data are therefore complete, and the summary statistics are computed as in the complete-data setting.
In all other cases, the presence of missing values means that the data are no longer complete. For most of the sample statistics, the computations proceed by using the available information for each statistic. For instance, the sample mean vector is obtained by computing the mean of each variable separately, using only the observations available for that variable. In R, this is implemented by applying the colMeans() function with the option na.rm = TRUE. Similarly, the sample covariance matrix is computed using the cov() function with the argument use = "pairwise.complete.obs". In this approach, the covariance for each pair of variables is based on all available pairs of complete observations for those two variables.
If missing = "ml" (or "ml.x"), additional sample statistics are computed for every missing pattern: the sample mean vector and the sample covariance matrix of the observations that belong to the pattern (the latter set to zero if the pattern contains only a single observation), together with the set of variables that are observed in the pattern and the number of observations that share it. These pattern-wise statistics are returned by lavInspect(fit, "patterns_stats"), as a list with one element per pattern (with components cov, mean, freq, and var_idx).
If sampling weights are supplied, they are incorporated into the computation of the summary statistics. In the case of multiple groups, these pattern-based summary statistics are computed separately for each group.
The pattern-based summary statistics are subsequently used during model estimation when evaluating the loglikelihood of the data under the current set of parameter values. Specifically, lavaan computes the loglikelihood for each missing-data pattern, making efficient use of the precomputed statistics.
When the missing option is set to "ml", "ml.x", "two.stage", or "robust.two.stage", lavaan employs maximum likelihood estimation to obtain the sample mean vector and sample covariance matrix in the presence of missing values. This is achieved with the Expectation–Maximization (EM) algorithm, separately for each group (the algorithm is derived in appendix D.9.7). The results are the estimates of the unrestricted model discussed in Section 5.7; in this setting, both lavInspect(fit, "h1") and lavInspect(fit, "sampstat") return them.
5.6.7 Multilevel data
If the data are clustered but the model does not include a multilevel structure, the clustering has no effect on the computation of the sample statistics (with the exception of the \boldsymbol{\Gamma} matrix).
In contrast, if the model specifies multiple levels, a set of intermediate summary statistics is computed that the two-level estimation routines build on: the cross product of the level-1 data, the level-2 data (one row per cluster), the sample means and covariances for each distinct cluster size, the loglikelihood of the exogenous covariates alone (under an unrestricted model for these covariates), and the pooled within-cluster sample covariance matrix, defined as:
where J is the number of clusters, and N is the total number of observations.
All of these intermediate statistics are returned by lavInspect(fit, "sampstat_2l"), as a list with elements such as sigma_w, y1y1, y2, mean_d, cov_d, and loglik_x (the manual page of lavInspect() lists them all). If conditional_x = TRUE, a larger set is computed. In ordinary use, however, the relevant quantities are the level-specific means and covariances of the unrestricted two-level model, returned by lavInspect(fit, "sampstat") (a list with a within element and one element named after the cluster variable) and by lavInspect(fit, "h1"); their estimation is described in Section 5.7.
Two-level data can also be combined with the (diagonally) weighted least squares estimators (WLS, DWLS, and ULS). For these estimators, the vector of ‘sample statistics’ (lavInspect(fit, "wls_obs")) contains the estimated statistics of the unrestricted two-level model: for continuous data, the means and (co)variances at the within and the between level; when some variables are ordered categorical, the within block contains thresholds, variances (continuous variables only), and within-level correlations. In the continuous case, these statistics are the estimates of the unrestricted two-level model (see Section 5.7); in the categorical case, they are obtained by stage-wise (univariate and bivariate) estimation of the unrestricted two-level model, the two-level analogue of the three-stage approach used for single-level categorical data (see Section 16.11). The corresponding Gamma matrix is a cluster-based sandwich estimate.
5.6.8 Ordered categorical data
When some or all of the observed variables are ordered categorical, the sample statistics differ substantially from those used with continuous data. Instead of sample means and covariances, lavaan relies on thresholds and correlations between the underlying continuous latent response variables.
The technical details of how these sample statistics are computed are given in Section 14.4.1 to Section 14.4.3.
When no exogenous (x) variables are present, lavInspect(fit, "sampstat") returns the following sample statistics:
cov: The covariance or correlation matrix (\mathbf{S}). Depending on the measurement level of the variables, this includes tetrachoric correlations (binary–binary), biserial correlations (binary–continuous), polychoric correlations (ordered–ordered), polyserial correlations (ordered–continuous), or ordinary covariances (continuous–continuous). For ordered categorical variables, the variance (the diagonal element) is fixed to one.
mean: The sample mean vector (\bar{\mathbf{y}}). Depending on the parameterization, the means for ordered categorical variables are typically set to zero.
th: The thresholds associated with the ordered categorical variables.
The vector of nonredundant sample statistics (lavInspect(fit, "wls_obs")) contains, in this order, the thresholds and the means of the continuous outcome variables (interleaved in the order of the variables; the means enter with a minus sign, see Section 14.4.4), the variances of the continuous outcome variables (if any), and the lower-triangular elements (excluding the diagonal) of the covariance matrix. The corresponding weight matrix (lavInspect(fit, "wls_v")) is used by estimator = "WLS", while estimator = "DWLS" uses only its diagonal, returned by lavInspect(fit, "wls_vd"). The Gamma matrix (lavInspect(fit, "gamma")) represents (N times) the asymptotic covariance matrix of the sample statistics.
If exogenous covariates (x) are present and conditional_x = TRUE (the default in the categorical setting), the covariates are first regressed out and the sample statistics reflect the residual information. In this case, lavInspect(fit, "sampstat") returns:
res.cov: The residual correlation or covariance matrix (\mathbf{S}_{y|x}).
res.th: The residual thresholds from the ordered probit regression on the exogenous covariates.
res.slopes: The regression coefficients from the ordered probit regression on the exogenous covariates.
res.int: The intercepts from the multivariate regression on the exogenous covariates (typically set to zero for ordered categorical variables).
cov.x: The sample covariance matrix of the exogenous covariates.
mean.x: The sample means of the exogenous covariates.
The vector of nonredundant sample statistics then contains, in this order, the residual thresholds and intercepts, the residual slopes (column by column, one covariate at a time), the residual variances for continuous outcomes (if any), and the lower-triangular elements (excluding the diagonal) of the residual covariance matrix (see Section 14.4.5 for an example); the weight matrix and the Gamma matrix refer to this residual vector. The thresholds that ignore the covariates (those of the marginal distribution of each ordered variable) remain available through lavInspect(fit, "res_th_nox").
Finally, lavInspect(fit, "zero_cell_tables") returns all two-way frequency tables that contain empty cells.
Most of the sample statistics described above are computed by internal functions of the lavaan package; the corresponding source files are mapped in the implementation notes at the end of this chapter (Section 5.8).
5.7 The unrestricted model
In structural equation modeling, the unrestricted or saturated model (often referred to as the \mathsf{H}_1 model) plays a central role in the assessment of model fit. The unrestricted model is defined as the model that places no constraints on the observed sample statistics. In other words, it is a model that fits the data perfectly by reproducing the sample means, variances, covariances, thresholds, and any other relevant summary statistics exactly. Because of this property, the unrestricted model has zero degrees of freedom.
The importance of the unrestricted model lies in its role as a benchmark. Model fit in SEM is evaluated by comparing the fit of the user-specified (restricted or \mathsf{H}_0) model against the unrestricted model. This comparison forms the basis of the likelihood ratio test (LRT), and many derived fit indices (such as CFI, TLI, and RMSEA) are defined relative to the unrestricted model. Without a properly defined unrestricted model, it would not be possible to compute these standard measures of fit.
The model-implied statistics of the unrestricted model (means, variances, covariances, slopes, and thresholds) are also an essential ingredient in the estimation process. They are used to generate starting values for the free parameters and to establish lower and upper bounds for certain parameters when needed.
5.7.1 The model-implied statistics of the unrestricted model
lavaan keeps the estimates of the unrestricted model inside the fitted object, in two parts: the model-implied statistics of the unrestricted model, returned by lavInspect(fit, "h1"), and its loglikelihood per group, where applicable, returned by lavInspect(fit, "h1_logl"); the sum over the groups is the unrestricted.logl fit measure. The counterpart for the fitted model is lavInspect(fit, "logl").
The contents of the model-implied statistics depend on whether exogenous covariates (x) are included in the model and on the value of the conditional_x argument. When no exogenous covariates are present, or when conditional_x = FALSE, lavInspect(fit, "h1") returns:
cov: the model-implied covariance (or correlation) matrix under the unrestricted model.
mean: the model-implied mean vector under the unrestricted model.
th: the model-implied thresholds under the unrestricted model.
The covariance (or correlation) matrix is always included. Means are returned only when a mean structure is specified (meanstructure = TRUE). Thresholds are included only if the model contains ordered categorical variables.
If exogenous covariates are present and conditional_x = TRUE, the model-implied statistics are:
res.cov: the model-implied residual covariance (or correlation) matrix under the unrestricted model.
res.int: the model-implied intercepts from the (unrestricted) multivariate regression on the exogenous covariates.
res.th: the residual thresholds under the unrestricted model.
res.slopes: the model-implied regression coefficients from the (unrestricted) multivariate regression on the exogenous covariates.
cov.x: the sample covariance matrix of the exogenous covariates.
mean.x: the sample means of the exogenous covariates.
In a multiple-group analysis, the unrestricted model also carries the group weights: the logarithm of the (effective) number of observations in each group, returned by lavInspect(fit, "group_w").
5.7.2 Extracting the unrestricted model-implied statistics
After a model has been fitted, the model-implied statistics of the unrestricted model can be extracted using the command lavInspect(fit, "h1"). Consider the following illustration with a one-factor model:
model <-'f =~ x1 + x2 + x3 + x4'fit <-sem(model, data = HolzingerSwineford1939)lavInspect(fit, "h1")
Because no mean structure was specified, only the model-implied covariance matrix is returned. In this example, since the data are continuous and complete (i.e., without missing values), the model-implied covariance matrix is identical to the sample covariance matrix returned by lavInspect(fit, "sampstat"):
The user-specified model is not unrestricted, which is evident from the nonzero degrees of freedom:
lavInspect(fit, "test")$standard$df
[1] 2
This occurs because the model includes only 8 free parameters, whereas the unrestricted model has 10 free parameters, corresponding to the 10 nonredundant elements of the covariance matrix. Consequently, the model-implied covariance matrix of the user model (\mathsf{H}_0) differs from that of the unrestricted model:
The likelihood ratio test is then obtained by taking the difference between these two loglikelihood values and multiplying by minus two:
lrt <--2* (logl_h0 - logl_h1)unname(lrt)
[1] 11.798
This statistic is commonly referred to in the literature as the chi-square test statistic, and it can be requested directly as follows:
lavTest(fit, test ="standard", output ="text")
Model Test User Model:
Test statistic 11.798
Degrees of freedom 2
P-value (Chi-square) 0.003
5.7.3 Estimating the unrestricted model-implied statistics
Estimating the parameters of the unrestricted model is straightforward under ideal conditions, such as when the data are complete and all variables are continuous. In this setting, the sample means and covariances can be computed directly using standard formulas. Since this information is already available among the sample statistics, the required quantities can simply be copied.
Estimation becomes more complex in less ideal scenarios. When missing values are present, iterative procedures such as the Expectation–Maximization (EM) algorithm may be required to estimate the sample statistics. Likewise, when some or all of the endogenous variables are ordered categorical, the relevant summary statistics consist of thresholds and polychoric (or polyserial) correlations. These cannot be obtained directly from raw frequency tables and instead require iterative estimation methods.
The sample statistics and the \mathsf{H}_1 model-implied statistics therefore coincide in the simplest settings and differ in the others. To avoid confusion, lavInspect(fit, "sampstat") returns the \mathsf{H}_1 estimates whenever they are available, so that both keywords agree in every setting. The details are provided below:
Setting 1, single level with missing = "listwise" (or "pairwise"): this is the most common setting, and it applies under the following conditions:
no multilevel structure is present (lavInspect(fit, "nlevels") equals 1), and
the data contain no missing values, or the missing argument has been set to "listwise" or "pairwise".
This setting covers the majority of use cases, including situations where some variables are ordered categorical and when a conditional analysis is requested (conditional_x = TRUE).
For continuous data, missing = "pairwise" fits the pairwise-complete sample moments. There is no suitable asymptotic covariance matrix for these moments, and the casewise scores contain missing values, so with the ML and GLS estimators only se = "standard" or the bootstrap, and the standard, Bollen–Stine, or normal-theory Browne residual tests are available; any other request stops with an error that suggests missing = "ml" instead. The least squares estimators (WLS, DWLS, ULS, and DLS) compute their \boldsymbol{\Gamma} from the pairwise-complete crossproducts and keep their robust standard errors and scaled tests, as in the categorical setting (Section 14.8). When the data are in fact complete, pairwise deletion is listwise deletion, and nothing changes.
In this case, no additional computations are required, as all relevant sample statistics are already available; the \mathsf{H}_1 model-implied statistics are simply copies of them.
Setting 2, single level with missing = "ml" (or "two.stage"): this setting applies only when the following conditions hold:
all variables are continuous,
the data contain missing values, and
the missing argument is set to one of "ml", "ml.x", "two.stage", or "robust.two.stage".
In this scenario, the expectation–maximization (EM) algorithm is employed to obtain maximum likelihood estimates of the means and covariances of the observed variables (the algorithm is derived in appendix D.9.7, and the asymptotic covariance matrix of the resulting estimates in appendix D.9.6). The em_h1_args option controls this run as well; its single-level defaults (currently at most 500 iterations and a tolerance of 10^{-5} on the change in the estimates) differ from the two-level ones given under Setting 3.
This setting also covers conditional_x = TRUE. The exogenous covariates must then be complete (missing = "ml.x" is not supported; cases with missing x-values are removed listwise). Because the x-values are complete, the joint normal likelihood factorizes as f(y \mid x) \, f(x) with variation-independent parameter blocks: the joint (y, x) moments of the unrestricted model are estimated by the same EM algorithm, and the saturated moments of the conditional model (residual intercepts, slopes, and residual covariances) are obtained by partitioning the joint EM moments. For the two-stage variants ("two.stage" and "robust.two.stage"), the combination with conditional_x = TRUE is currently limited to estimator = "ML".
An exception arises when the coverage of a pair of variables is exactly zero, meaning that no observations contain valid values for both variables. In this special case, the current EM implementation cannot be applied. Instead, lavaan() is called with missing = "ml" to obtain the full information maximum likelihood estimates of the means and covariances.
The resulting estimates become the cov and mean entries of the \mathsf{H}_1 model-implied statistics.
Setting 3, multilevel without missing data: this setting applies only under the following conditions:
all variables are continuous,
the data contain no missing values, or missing is set to "listwise", or "pairwise",
a multilevel structure is present (lavInspect(fit, "nlevels") greater than 1), and
the model contains only random intercepts (no random slopes).
In this case, it is necessary to compute the unrestricted means and covariances of the observed variables at each level. This is accomplished using the expectation–maximization (EM) algorithm (see Section 16.6.2).
The behavior of this EM algorithm can be controlled through the em_h1_args argument, a list with elements such as the maximum number of iterations (max_iter), the convergence tolerance (tol), and the acceleration scheme (acceleration). One element deserves special mention: non_pd_action determines what happens when the EM algorithm produces a (near) singular within-level or between-level covariance matrix, for example because one of the between-level variances approaches zero. By default (non_pd_action = "warn"), a warning is issued and estimation continues; setting it to "stop" turns this condition into an error.
Setting 4, multilevel with missing = "ml": this setting is similar to Setting 3 but allows for missing data, with the missing argument set to "ml" (or "ml.x"). By default, lavaan uses a dedicated EM algorithm for two-level data with missing values (see Section 16.9), and the em_h1_args argument applies here as well. An alternative strategy, which fits the unrestricted model directly by calling the lavaan() function with a Cholesky parameterization of the level-specific covariance matrices, remains available by setting the option h1_missing_method = "fiml" (the default is "em").
5.7.4 Computing the unrestricted statistics directly: lavH1()
Throughout this section, the \mathsf{H}_1 statistics appeared as a by-product of fitting a model. They can also be computed directly, without specifying a model: the lavH1() function takes a data frame and returns the unrestricted (\mathsf{H}_1) summary statistics:
All the data-related options of this chapter apply: group= for multiple groups, cluster= for two-level data (returning within- and between-level statistics plus the intraclass correlations), ordered= for thresholds and polychoric correlations, sampling_weights=, and missing = "ml" for EM estimates of the saturated moments. The latter is a convenient way to obtain FIML estimates of the descriptive statistics one would report in a Method section:
A model syntax (or a fitted lavaan object) may be given as the first argument, but it is used only to determine which variables are involved, their roles (exogenous, ordered, per level), and the data-related options, so that the result is exactly the \mathsf{H}_1 information a fit of that model would use.
Besides the default list, two other output forms are available. With output = "lavaan", the unrestricted model itself is returned as a fitted lavaan object, whose summary() reports standard errors, Wald z-statistics and p-values for the summary statistics themselves. Combined with correlation = TRUE, this answers the common applied question of which correlations differ significantly from zero (with the proper correlation-structure treatment of Section 12.5 applied internally). And with output = "lavMoments", the function returns a lavMoments object that packages everything a moments-only reanalysis needs (the sample statistics, the th.idx attribute, the wls_v and nacov matrices where relevant, and the matching options) in a form that can be passed directly as the data= argument of the fitting functions; this use is described in Section 5.3.
Finally, a related function deserves mention: lavCor() shares its machinery with lavH1(), but was designed for one specific and very common request: quick access to the polychoric, polyserial, and Pearson correlations of a dataset in the categorical setting, without specifying any model (it is used in Section 14.4.2). lavH1() generalizes the idea to the full set of \mathsf{H}_1 statistics: means, thresholds, (residual) covariances, per group and per level, with the three output forms above. Both functions leave a fitted object untouched: to extract the \mathsf{H}_1 statistics that were computed during a fit, use lavInspect(fit, "h1").
5.8 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 three stages of this chapter correspond to three slots of the fitted object: @Data (an object of class lavdata, created by lavData()), @SampleStats (class lavsamplestats), and @h1 (a list with the elements implied and logl). Their layout is internal and subject to change; str() on a slot shows the current layout for those who need it, but nothing in the main text depends on it. Two conventions of that layout are worth knowing when reading the source: most elements are lists with one entry per group, even for a single group, and the Gamma matrix, the weight matrix, and the vector of sample statistics are called NACOV, WLS.V, and WLS.obs throughout the code. Table 5.2 maps the computations of this chapter to their source files.
Table 5.2: Source files behind the sample statistics and the \mathsf{H}_1 model.
Topic
File(s)
sample statistics from raw data or from moments (lav_samp_from_data(), lav_samp_from_moments()); two-level intermediate statistics (lav_samp_cl_patterns())
\mathsf{H}_1 dispatching logic; lavH1() and lavCor() (lav_h1_lavobject())
lav_h1_implied.R lav_lavh1.R
Browne, M. W. (1984). Asymptotic distribution-free methods in the analysis of covariance structures. British Journal of Mathematical and Statistical Psychology, 37(1), 62–83.
Neudecker, H., & Wesselman, A. M. (1990). The asymptotic variance matrix of the sample correlation matrix. Linear Algebra and Its Applications, 127, 589–599. https://doi.org/10.1016/0024-3795(90)90363-H
Storing a copy of the data internally is convenient, as it allows several functions (e.g., lavPredict(), which computes factor scores) to access the data directly, without requiring the user to pass it again. However, for very large datasets, keeping an internal copy is memory-inefficient. Future versions of lavaan may avoid storing the data internally for this reason.↩︎
Estimation for models with multiple clustering variables (i.e., more than two levels) is not supported in version 0.7-4.↩︎