16  Multilevel SEM

16.1 SEM for clustered data

Many datasets in the social and behavioral sciences have a nested or clustered structure: students are nested within schools, employees within companies, patients within hospitals, repeated measures within individuals. Observations from the same cluster tend to be more alike than observations from different clusters: students in the same school share teachers and school climate. This within-cluster dependence violates the independence assumption that underlies all the estimators discussed in chapter 7. Ignoring it does little harm to the point estimates (they typically remain consistent), but it can severely distort inference: standard errors tend to be too small, test statistics too large, and the nominal Type I error rates are no longer maintained (see, e.g., Hox et al., 2018).

Two broad strategies exist for dealing with clustered data. The design-based approach keeps the single-level model, treats the clustering as a nuisance feature of the sampling design, and corrects the standard errors and test statistics after the fact. The model-based approach makes the clustering part of the model itself: variables are decomposed into within-cluster and between-cluster components, and a (potentially different) structural model is specified at each level. This chapter is about the model-based approach: the two-level structural equation model, specified in lavaan by combining the cluster= argument with level: blocks in the model syntax. The design-based approach was already covered in chapter 8 (see se = "robust.cluster" and se = "robust.cluster.sem" in Section 8.4.7); we briefly recapitulate it below, because the choice between the two strategies is a genuine modeling decision, not a software issue.

Two versions of the two-level model are discussed. In the random-intercept model, the clusters differ in the level of their variables only: each cluster has its own intercepts, but the relations among the variables within a cluster are the same everywhere. This is the classical two-level SEM, and most of the chapter is devoted to it, because it is the setting in which the data can be summarized by a within and a between covariance matrix, and in which an unrestricted model, a chi-square test statistic and fit measures exist. In the random-slope model, one or more regression coefficients of the within model vary across clusters as well, as in the linear mixed model. Users who come from mixed models (and from software such as the lme4 package) usually start here. The random-slope model needs a different likelihood, which is conditional on the covariates, and it is discussed in a separate section (Section 16.13) that builds on the material for the random-intercept model.

The chapter proceeds as follows. We first define the two-level random-intercept model and its within/between decomposition, and summarize what is (and is not) supported in lavaan version 0.7-4 (Section 16.3). We then discuss the model syntax (Section 16.4), using the Demo.twolevel dataset as a running example. The core of the chapter derives the two-level log-likelihood and shows how lavaan evaluates it cluster by cluster (Section 16.5), how the unrestricted (\mathsf{H}_1) model is estimated by an EM algorithm (Section 16.6), and how the model parameters themselves are estimated (Section 16.7). Next, we cover standard errors and test statistics (Section 16.8), missing data (Section 16.9), sampling weights at both levels (Section 16.10), two-level least-squares estimation and its use for categorical endogenous variables (Section 16.11), and the various ways to inspect a fitted two-level model (Section 16.12). Random slopes are then treated in a separate section (Section 16.13): the syntax, the conditional likelihood that replaces the two-level likelihood of the earlier sections, the way the slopes are represented in the model matrices, and the consequences for estimation and inference. We close with autoregressive models for long panel data with lagged variables, which rely on the same conditional likelihood (Section 16.14).

16.2 Design-based versus model-based

When only a cluster= argument is provided (without level: blocks in the model syntax), lavaan fits an ordinary single-level model, but it automatically switches to cluster-robust inference: the default standard errors become se = "robust.cluster" and the default test becomes test = "yuan.bentler.mplus". The point estimates are exactly the same as in an analysis that ignores the clustering; only the standard errors and the test statistic change. Internally, the casewise score contributions are summed within each cluster before the meat of the sandwich estimator is formed (see Equation 8.12 in Section 8.2.4), and the same idea underlies the cluster-corrected \hat{\boldsymbol{\Gamma}} matrix used by se = "robust.cluster.sem" (Section 8.4.7). This design-based route treats the clusters as the independent sampling units and is available for continuous, categorical, and incomplete data.

The design-based approach answers a limited question: it protects the inference for the pooled (total) associations among the variables. It cannot tell us whether the structure of the associations differs across levels, for example whether the correlation between school climate and achievement at the school level differs from the correlation between the corresponding student-level variables. Whenever the between-cluster structure is itself of scientific interest, or whenever cluster-level (level-2) variables enter the model, a model-based approach is needed. The rest of this chapter is devoted to it.

The distinction between the two approaches comes from the survey literature, where they are known as the aggregated and the disaggregated analysis of complex survey data (Skinner et al., 1989). In the SEM context, Wu and Kwok (2012) compared the design-based single-level approach with the model-based two-level approach in a simulation study, and discuss when each of them can be used.

16.3 The two-level random-intercept model

16.3.1 The within/between decomposition

Consider a continuous response vector \mathbf{y}_{ji} observed for unit i (i = 1, \ldots, n_j) inside cluster j (j = 1, \ldots, N_J). The two-level random-intercept model decomposes each observation into a grand mean, a cluster-specific deviation, and a unit-specific deviation:

\mathbf{y}_{ji} = \boldsymbol{\mu}+ \mathbf{y}_{B,j} + \mathbf{y}_{W,ji}, \tag{16.1}

where the between component \mathbf{y}_{B,j} (the random intercept of cluster j) and the within component \mathbf{y}_{W,ji} are independent, zero-mean random vectors with covariance matrices \boldsymbol{\Sigma}_B and \boldsymbol{\Sigma}_W, respectively. The total covariance is the sum of the two parts:

\text{Var}(\mathbf{y}_{ji}) = \boldsymbol{\Sigma}_B + \boldsymbol{\Sigma}_W. \tag{16.2}

This is an orthogonal decomposition of the population covariance matrix; it holds by construction and does not restrict the data in any way (Goldstein & McDonald, 1988; Muthén, 1994). The model is specified in the next step: a structural equation model is imposed on each component separately. Using the LISREL representation of Section 4.1, the within model generates

\boldsymbol{\Sigma}_W(\boldsymbol{\vartheta}) = \boldsymbol{\Lambda}_W (\mathbf{I} - \mathbf{B}_W)^{-1} \boldsymbol{\Psi}_W (\mathbf{I} - \mathbf{B}_W^{\prime})^{-1} \boldsymbol{\Lambda}_W^{\prime} + \boldsymbol{\Theta}_W, \tag{16.3}

and the between model generates

\boldsymbol{\mu}_B(\boldsymbol{\vartheta}) = \boldsymbol{\nu}_B + \boldsymbol{\Lambda}_B (\mathbf{I} - \mathbf{B}_B)^{-1} \boldsymbol{\alpha}_B, \qquad \boldsymbol{\Sigma}_B(\boldsymbol{\vartheta}) = \boldsymbol{\Lambda}_B (\mathbf{I} - \mathbf{B}_B)^{-1} \boldsymbol{\Psi}_B (\mathbf{I} - \mathbf{B}_B^{\prime})^{-1} \boldsymbol{\Lambda}_B^{\prime} + \boldsymbol{\Theta}_B, \tag{16.4}

with a separate set of model matrices per level. Each level is simply another block: a two-level model has two blocks per group, with a full set of LISREL matrices for each block (see Section 4.3.3). Latent variables never cross levels: a factor defined in the within block only loads on within components, and a factor defined in the between block only loads on between components (random intercepts).

Because only the between part carries a mean structure, the mean vector \boldsymbol{\mu} in Equation 16.1 is absorbed into \boldsymbol{\mu}_B(\boldsymbol{\vartheta}): the within intercepts of variables that appear at both levels are fixed to zero, and their means are modeled at the between level (see Section 16.4.3).

Under multivariate normality of both components, the n_j observations of cluster j, stacked into one long vector, are jointly normal with mean \boldsymbol{1}_{n_j} \otimes \boldsymbol{\mu}_B(\boldsymbol{\vartheta}) and covariance matrix

\boldsymbol{\Omega}_{j} = \boldsymbol{1}_{n_j}\boldsymbol{1}_{n_j}^{\prime} \otimes \boldsymbol{\Sigma}_B(\boldsymbol{\vartheta}) + \mathbf{I}_{n_j} \otimes \boldsymbol{\Sigma}_W(\boldsymbol{\vartheta}). \tag{16.5}

Observations from different clusters are independent. Equation Equation 16.5 shows why clustered observations are dependent (the common \boldsymbol{\Sigma}_B block links all pairs of units within a cluster) and also why the model is called a random-intercept model: every unit in the cluster shares the same between deviation \mathbf{y}_{B,j}, shifting the intercept of the within model by a cluster-specific amount. Random slopes (regression coefficients that vary across clusters) change the covariance structure of a cluster in a more fundamental way; they are the topic of Section 16.13.

16.3.2 The intraclass correlation

For a single variable y_p that varies at both levels, the intraclass correlation coefficient (ICC) is the proportion of its total variance that is located at the between level:

\mathrm{ICC}_p = \frac{(\boldsymbol{\Sigma}_B)_{pp}} {(\boldsymbol{\Sigma}_B)_{pp} + (\boldsymbol{\Sigma}_W)_{pp}}. \tag{16.6}

The ICC equals the correlation between two randomly chosen units from the same cluster and is the standard measure of the strength of the clustering. In lavaan, lavInspect(fit, "icc") computes Equation 16.6 from the unrestricted (\mathsf{H}_1) estimates of \boldsymbol{\Sigma}_W and \boldsymbol{\Sigma}_B (see Section 16.6), so the reported ICCs do not depend on the fitted model.

16.3.3 What is (and is not) supported

The multilevel capabilities of lavaan, as of version 0.7-4, can be summarized as follows:

  • Two levels only: the model syntax accepts exactly two distinct level: blocks per group. More than one clustering variable can be passed to the cluster= argument, but estimation for three or more levels is not supported as of version 0.7-4.

  • Random intercepts and random slopes: most of this chapter is about the random-intercept model of Section 16.3.1. Random slopes, for observed and for latent covariates, are requested with the rv() modifier (Section 16.13). They are estimated from a different (conditional) likelihood, and come with restrictions of their own (in particular, no chi-square test statistic). The same restrictions apply to autoregressive models for long panel data (Section 16.14).

  • Continuous data with ML is the most fully supported setting: complete or missing (missing = "ml") data, conditional_x = FALSE (the default) or conditional_x = TRUE (complete data only), single or multiple groups (where the grouping variable must be defined at the cluster level or above; see Section 2.7.3).

  • Least-squares estimation (GLS/WLS/DWLS/ULS) for two-level data is available for complete data only (see Section 16.11.1). WLS, DWLS and ULS are the only route that supports categorical (ordinal) endogenous variables in a two-level model (e.g., estimator = "WLSMV"; see Section 16.11); estimator = "GLS", with its normal-theory weight matrix, is for continuous data only. Two-level categorical data with ML or PML is not supported.

  • Sampling weights are supported at both levels, for continuous data: the sampling_weights= argument gives the weights of the level-1 units within their cluster, and the sampling_weights_cluster= argument the weights of the clusters. They can be used with ML (complete or missing data) and with the least-squares estimators (except GLS), but not with conditional_x = TRUE or with random slopes (see Section 16.10).

  • Not supported in a two-level analysis: correlation structures (correlation = TRUE), sample_cov_robust = TRUE, and the missing = "two.stage" method. Bootstrapping is available (with complete and with missing data) and resamples entire clusters.

16.4 Model syntax

16.4.1 Level blocks

A two-level model is specified by dividing the model syntax into blocks with the level: block operator (see Section 2.7.2, and Section 2.7 for the general block mechanism), and by providing a cluster= argument. As a running example, we use the Demo.twolevel dataset that ships with lavaan: a simulated dataset with N = 2500 observations nested in N_J = 200 clusters, six within-level variables (y1–y3, x1–x3), two cluster-level covariates (w1, w2), and a cluster identifier (cluster):

model <- '
  level: within
    fw =~ y1 + y2 + y3
    fw ~ x1 + x2 + x3
  level: between
    fb =~ y1 + y2 + y3
    fb ~ w1 + w2
'
fit <- sem(model, data = Demo.twolevel, cluster = "cluster")

The labels on the right-hand side of level: are free: level: 1 and level: 2, level: within and level: between, or any pair of custom names (level: student / level: school) are all accepted. Which block describes the within (level-1) part of the model and which block the between (level-2) part is decided as follows. If the labels reveal which level is which, the labels decide, and the blocks may be written in any order. This is the case in three situations:

  • both labels are numbers: the smallest number is the within level, so that a level: 2 block followed by a level: 1 block is read as intended;

  • the labels within and between (in lower or upper case) are used: they have their obvious meaning;

  • a label equals the name of the cluster variable (for example level: cluster when cluster = "cluster"): this block is the between level.

In all other cases, the order of appearance is used: the first block describes the within level, and the second block the between level. This holds in particular for a pair of custom names that lavaan cannot interpret, such as level: student and level: school when the cluster variable has a different name; writing the school block first would then silently exchange the two levels (often, but not always, followed by an error about between-level variables that vary within clusters). Whatever the order in the syntax, the within level always comes first in the parameter table and in the output. Note that in earlier versions of lavaan the order of appearance was the only rule: the first block was the within level, even if it was labeled level: 2.

A block may be opened more than once (for example, a second level: within block after the between block): blocks with the same label are merged, and the roles of the variables are determined from the merged block. The level keyword itself is matched case-insensitively. Two rules are strictly enforced: the model syntax must contain a model for every level (a between block cannot be omitted, although it may be saturated or even empty of structure; see Section 16.4.4), and when level: blocks are present, the cluster= argument is mandatory. In the parameter table, each level becomes a separate block, and both a level and a block column are present (see Section 2.7.3).

The summary() output reflects the two-level structure: the header reports the number of clusters, and the parameter estimates are printed per level:

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

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        20

  Number of observations                          2500
  Number of clusters [cluster]                     200

Model Test User Model:
                                                      
  Test statistic                                 8.092
  Degrees of freedom                                10
  P-value (Chi-square)                           0.620
                                                      
  Browne's residual (NT model-based) test             
  Test statistic                                 7.907
  Degrees of freedom                                10
  P-value (Chi-square)                           0.638

Parameter Estimates:

  Standard errors                             Standard
  Information                                 Observed
  Observed information based on                Hessian


Level 1 [within]:

Latent Variables:
                   Estimate  Std.Err  z-value  P(>|z|)
  fw =~                                               
    y1                1.000                           
    y2                0.774    0.034   22.671    0.000
    y3                0.734    0.033   22.355    0.000

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  fw ~                                                
    x1                0.510    0.023   22.037    0.000
    x2                0.407    0.022   18.273    0.000
    x3                0.205    0.021    9.740    0.000

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y1                0.986    0.046   21.591    0.000
   .y2                1.066    0.039   27.271    0.000
   .y3                1.011    0.037   27.662    0.000
   .fw                0.546    0.040   13.539    0.000


Level 2 [cluster]:

Latent Variables:
                   Estimate  Std.Err  z-value  P(>|z|)
  fb =~                                               
    y1                1.000                           
    y2                0.717    0.052   13.824    0.000
    y3                0.587    0.048   12.329    0.000

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  fb ~                                                
    w1                0.165    0.079    2.093    0.036
    w2                0.131    0.076    1.715    0.086

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y1                0.024    0.075    0.327    0.743
   .y2               -0.016    0.060   -0.269    0.788
   .y3               -0.042    0.054   -0.777    0.437

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y1                0.058    0.047    1.213    0.225
   .y2                0.120    0.031    3.825    0.000
   .y3                0.149    0.028    5.319    0.000
   .fb                0.899    0.118    7.592    0.000

16.4.2 Variable roles: within-only, between-only, shared

Every observed variable in a two-level model plays one of three roles, and lavaan infers the role from where the variable appears in the syntax:

  • a variable that appears in both blocks (here y1, y2, y3) is shared; it is decomposed as in Equation 16.1, and its latent between component (its random intercept) is what the between model describes;

  • a variable that appears only in the within block (here x1, x2, x3) is within-only: it is assumed to have no between-level variance component in the model, and its (co)variances are contained entirely in \boldsymbol{\Sigma}_W;

  • a variable that appears only in the between block (here w1, w2) is between-only: it is a genuine cluster-level variable that takes the same value for every unit in a cluster.

lavaan checks the between-only variables against the data: if a variable that is used exclusively at level 2 shows non-zero variance within clusters, an error is raised (“Some between-level (only) variables have non-zero variance at the within-level”). Conversely, declaring a variable as within-only does not make its observed cluster means zero; it merely asserts that the between-level variance is zero in the population. If this assertion is questionable, the variable can be included at both levels, at the cost of estimating its between-level variance (which may be near zero, a common source of estimation problems; see Section 16.7.3).

A within-only covariate is not centered by lavaan. If the observed score mixes within- and between-cluster variance and both effects are of interest, either include the variable at both levels (implicit latent centering: the model decomposes it into latent components), or center it explicitly (observed centering) before the analysis. The two approaches estimate different contextual effects; see Lüdtke et al. (2008) for a discussion of the trade-offs.

16.4.3 Intercepts and means

For a shared variable, only the sum of its within and between intercepts is identified: adding a constant to \boldsymbol{\mu}_W and subtracting it from \boldsymbol{\mu}_B leaves the distribution of the data unchanged. lavaan resolves this by convention: the within intercepts of shared variables are fixed to zero, and their grand means are modeled at the between level. An intercept formula such as y1 ~ 1 is therefore only meaningful inside the between block, where it represents the overall (grand) mean of y1; placing free intercepts for shared variables in the within block would render the model unidentified. Within-only variables keep their intercepts at level 1 (no other level is available for them), and between-only variables have their means at level 2. A subset of the parameter table shows this directly:

subset(parameterTable(fit), op == "~1",
       select = c("lhs", "op", "block", "level", "free", "ustart"))
   lhs op block   level free ustart
17  y1 ~1     1  within    0      0
18  y2 ~1     1  within    0      0
19  y3 ~1     1  within    0      0
20  x1 ~1     1  within    0     NA
21  x2 ~1     1  within    0     NA
22  x3 ~1     1  within    0     NA
23  fw ~1     1  within    0      0
36  y1 ~1     2 between   18     NA
37  y2 ~1     2 between   19     NA
38  y3 ~1     2 between   20     NA
39  w1 ~1     2 between    0     NA
40  w2 ~1     2 between    0     NA
41  fb ~1     2 between    0      0

The within intercepts of y1–y3 are fixed (free = 0, ustart = 0), while their between intercepts are free parameters.

A fixed within intercept is not the same as a zero within mean. If a shared variable depends (directly, or through a within-level factor as in the running example) on a within-only covariate whose mean is not zero, its model-implied within mean is not zero either, and the between intercept equals the grand mean minus this within part: it is an intercept in the regression sense, the expected value when the covariates are zero. In Demo.twolevel the covariates x1–x3 have means close to zero, so the difference is hardly visible. To make it visible, we add a constant to x1 and fit a small regression model to the original and to the shifted data:

model_int <- '
  level: within
    y1 ~ x1
  level: between
    y1 ~ w1
'
Demo_shift <- Demo.twolevel
Demo_shift$x1 <- Demo_shift$x1 + 5
fit_int   <- sem(model_int, data = Demo.twolevel, cluster = "cluster")
fit_shift <- sem(model_int, data = Demo_shift,    cluster = "cluster")
round(rbind(original = coef(fit_int), shifted = coef(fit_shift)), 3)
         y1~x1 y1~~y1 y1~w1.lbetween y1~~y1.lbetween y1~1.lbetween
original 0.494   1.76          0.161           0.913         0.015
shifted  0.494   1.76          0.161           0.913        -2.455

Only the between intercept of y1 changes; everything else (the other estimates, their standard errors, and the test statistics, robust versions included) is the same. The grand mean of y1 is the same in both datasets (about 0.02), but in the shifted data it is no longer what the between intercept shows. Because this can be confusing, it is useful to know what each function reports for a shared variable.

The parameter estimates, as shown by summary(), coef() and parameterEstimates(), are the intercepts: zero (fixed) at the within level, and the regression intercept at the between level. The model-implied means, as returned by lavInspect(fit, "implied") or fitted(), are the means that the model implies for each level separately. The within mean of y1 is the slope times the mean of x1, and the between mean is the value that makes the sum equal to the grand mean:

lavInspect(fit_shift, "mean_ov")
$within
   y1    x1 
2.466 4.993 

$cluster
    y1     w1 
-2.446  0.052 

Neither of the two values is meaningful on its own; only their sum is identified. The observed (\mathsf{H}_1) statistics keep the convention of the first paragraph: the within mean of a shared variable is zero, and its total mean is stored at the between level:

lapply(lavInspect(fit_shift, "h1"), "[[", "mean")
$within
   y1    x1 
0.000 4.993 

$cluster
   y1    w1 
0.020 0.052 

A naive comparison of the last two outputs would suggest a large misfit in the means of y1 at both levels (about -2.47 and +2.47), although the model reproduces the mean of y1 perfectly. Therefore, whenever model-implied means are compared with the observed statistics, the implied means are first brought to the same convention: the implied within mean of a shared variable is added to its implied between mean, and is then set to zero. This is what lavResiduals() and resid() do, and with them all the quantities that are derived from the mean residuals (the standardized residuals and the SRMR of Section 16.12.2, and Browne’s residual-based tests of Section 16.8.3):

res <- resid(fit_shift)
res$within$mean
y1 x1 
 0  0 
res$cluster$mean
y1 w1 
 0  0 

The residuals of y1 are zero at both levels: at the within level because both the observed and the (adjusted) implied mean are zero by convention, and at the between level because the sum of the two implied parts equals the grand mean. In short, the within-level mean of a shared variable always appears as zero in the observed statistics and in the residuals, even if the model-implied within mean is not zero, and the between-level value then stands for the sum of the within and the between part.

16.4.4 Saturating a level

Any level can be left unstructured by saturating it: all variances and covariances free, no latent variables. This is useful both as a baseline for isolating misfit at the other level (Ryu & West, 2009), as discussed in Section 10.7, and as a way to leave a level unrestricted while the model for the other level is being developed. For example, a within-level factor model combined with a saturated between level:

model_wsat <- '
  level: within
    fw =~ y1 + y2 + y3
    fw ~ x1 + x2 + x3
  level: between
    y1 ~~ y1 + y2 + y3
    y2 ~~ y2 + y3
    y3 ~~ y3
'
fit_wsat <- sem(model_wsat, data = Demo.twolevel, cluster = "cluster")
fitMeasures(fit_wsat, c("chisq", "df", "pvalue"))
 chisq     df pvalue 
 1.410  6.000  0.965 

Since the saturated between block cannot contribute misfit, the remaining chi-square reflects the within model only. This partially-saturated construction is automated by fitMeasures(fit, level = "within") (see Section 16.12.2); note that the automated version keeps w1 and w2 in the (saturated) between block, whereas we dropped them above, so the two statistics differ slightly. As a technical aside: when an entire level is saturated, lavaan temporarily fixes the parameters of that block at their \mathsf{H}_1 values during optimization (they are already the ML estimates), which reduces the dimension of the search space; this behavior is controlled by the optim_fix_saturated option (default TRUE; see Section 16.7).

16.4.5 The same factor at both levels

In the running example, the factor fw and the factor fb are defined by the same indicators, but they are different latent variables: fw is defined in the within block and explains within-cluster covariance, fb is defined in the between block and explains covariance among the random intercepts. Nothing forces their loadings to be equal. A popular restriction, however, is cross-level measurement invariance: the same loading matrix at both levels, so that the between factor can be interpreted as the latent cluster mean of the within factor (Mehta & Neale, 2005). In lavaan, this is imposed with ordinary labels:

model_inv <- '
  level: within
    fw =~ y1 + l2*y2 + l3*y3
  level: between
    fb =~ y1 + l2*y2 + l3*y3
'
fit_inv <- sem(model_inv, data = Demo.twolevel, cluster = "cluster")
coef(fit_inv)[1:2]
       l2        l3 
0.7332820 0.6643847 

Because labels are shared across blocks, these become simple equality constraints, and all the results of Section 7.7.7 apply. Under this restriction, it is also meaningful to compare the factor variances across levels, or to compute a factor-level ICC as \hat{\psi}_B / (\hat{\psi}_B + \hat{\psi}_W) using a := defined parameter.

Cross-level constraints have one side effect: when equality constraints link parameters from different levels, the level-specific fit measures of Section 10.7 are no longer defined (the levels can no longer be saturated one at a time without touching the other). The model itself is fitted as usual, without any warning, and the ordinary fit measures are available; lavaan simply skips the partially saturated fits. Only when level-specific fit measures are requested explicitly does lavaan stop with an error message:

fitMeasures(fit_inv, level = "between")
Error:
! lavaan->lav_fit_by_level_get():  
   level-specific fit measures are not available: the model contains 
   (equality) constraints involving parameters from different levels.

16.4.6 Exogenous covariates: fixed_x and conditional_x

Exogenous observed covariates are handled per level: in the example, x1–x3 are exogenous at the within level and w1–w2 at the between level. The default for two-level models is fixed_x = TRUE combined with conditional_x = FALSE: the covariates are part of the joint (normal) model, but their means and (co)variances are fixed to their sample-based values, which at each level are the values of the \mathsf{H}_1 (saturated) solution. The rows and columns of the information matrices that correspond to covariate-only moments are zeroed out, so these fixed moments do not contribute to standard errors or to the test statistic.

With conditional_x = TRUE, the model conditions on the exogenous covariates and the likelihood is expressed in terms of residual intercepts, slopes, and residual (co)variances per level. The two-level conditional likelihood, its analytic gradient, and the corresponding sufficient statistics are the two-level analogue of the single-level conditional likelihood of appendix D.8; the sufficient statistics are level-specific cross-products of residuals and covariates, computed per cluster size. One restriction applies: conditional_x = TRUE is only available for complete data (combining it with missing = "ml" stops with an error).

16.5 The two-level log-likelihood

16.5.1 Per-cluster contributions

Estimation proceeds by maximum likelihood under the normality assumptions of Section 16.3.1. Since clusters are independent, the log-likelihood is a sum of per-cluster contributions, each based on the n_j \, P-dimensional normal density with covariance matrix \boldsymbol{\Omega}_j of Equation 16.5. Evaluating that density naively would require inverting \boldsymbol{\Omega}_j, a matrix of order n_j \, P, for every cluster. This is not needed, because \boldsymbol{\Omega}_j has a special structure that admits closed-form determinant and quadratic-form expressions in terms of P \times P matrices only (McDonald & Goldstein, 1989); the derivation is given in appendix E.2. Write \bar{\mathbf{y}}_j for the vector of cluster means and

\mathbf{A}_j = \sum_{i=1}^{n_j} (\mathbf{y}_{ji} - \bar{\mathbf{y}}_j)(\mathbf{y}_{ji} - \bar{\mathbf{y}}_j)^{\prime}

for the within-cluster scatter matrix. Then, with \boldsymbol{\Sigma}_j = \boldsymbol{\Sigma}_W + n_j \boldsymbol{\Sigma}_B,

\log |\boldsymbol{\Omega}_j| = (n_j - 1) \log|\boldsymbol{\Sigma}_W| + \log|\boldsymbol{\Sigma}_j|, \tag{16.7}

and the log-likelihood contribution of cluster j becomes

\begin{aligned} \log L_j = -\frac{1}{2} \Bigl\{\; & n_j \, P \log(2\pi) + (n_j - 1) \log|\boldsymbol{\Sigma}_W| + \log|\boldsymbol{\Sigma}_j| + \mathrm{tr}\bigl[\boldsymbol{\Sigma}_W^{-1} \mathbf{A}_j\bigr] \\ & + n_j\, (\bar{\mathbf{y}}_j - \boldsymbol{\mu})^{\prime} \boldsymbol{\Sigma}_j^{-1} (\bar{\mathbf{y}}_j - \boldsymbol{\mu}) \;\Bigr\}, \end{aligned} \tag{16.8}

where \boldsymbol{\mu}= \boldsymbol{\mu}_B(\boldsymbol{\vartheta}) and, for readability, we suppressed the dependence of \boldsymbol{\Sigma}_W and \boldsymbol{\Sigma}_B on \boldsymbol{\vartheta}. The interpretation is transparent: each cluster contributes (n_j - 1) independent “within” deviations, which carry information about \boldsymbol{\Sigma}_W only, plus one cluster mean \bar{\mathbf{y}}_j, whose covariance matrix \boldsymbol{\Sigma}_B + \boldsymbol{\Sigma}_W / n_j = \boldsymbol{\Sigma}_j / n_j mixes the two levels. The total number of observations informing \boldsymbol{\Sigma}_W is therefore N - N_J, while \boldsymbol{\Sigma}_B is informed by only N_J cluster means. This is the fundamental asymmetry of two-level models: no matter how large N is, the between level is estimated from N_J units.

16.5.2 Sufficient statistics; balanced versus unbalanced data

Summing Equation 16.8 over clusters shows that the data enter only through a small set of sufficient statistics: the pooled within covariance matrix

\mathbf{S}_{PW} = \frac{1}{N - N_J} \sum_{j=1}^{N_J} \mathbf{A}_j, \tag{16.9}

and the cluster means \bar{\mathbf{y}}_j. Moreover, the “between” part of Equation 16.8 depends on j only through the cluster size n_j: two clusters of the same size share the same \boldsymbol{\Sigma}_j (and its inverse and determinant). lavaan exploits this by grouping the clusters into strata of equal size. For each distinct cluster size s (with N_s clusters of that size), it stores the average of the cluster means, \mathbf{m}_s, and their (ML) covariance matrix, \mathbf{C}_s; the between part of -2\log L for that stratum is then

N_s \Bigl\{ \log|\boldsymbol{\Sigma}_{(s)}| + s \, \mathrm{tr}\bigl[ \boldsymbol{\Sigma}_{(s)}^{-1} \bigl( \mathbf{C}_s + (\mathbf{m}_s - \boldsymbol{\mu})(\mathbf{m}_s - \boldsymbol{\mu})^{\prime} \bigr) \bigr] \Bigr\}, \qquad \boldsymbol{\Sigma}_{(s)} = \boldsymbol{\Sigma}_W + s\,\boldsymbol{\Sigma}_B. \tag{16.10}

For balanced data (all clusters the same size) there is a single stratum and a single \boldsymbol{\Sigma}_{(s)} to invert per likelihood evaluation; this is the classical balanced case for which McDonald and Goldstein (1989) and Muthén (1994) obtained simple estimators. For unbalanced data, the cost grows with the number of distinct cluster sizes, not with the number of clusters. In Demo.twolevel there are 200 clusters but only four distinct sizes (5, 10, 15, 20):

lavInspect(fit, "ncluster_size")
[1] 4
lavInspect(fit, "cluster_sizes")
[1]  5 10 15 20

These sufficient statistics are computed once, when the sample statistics are created, and stored with them: the matrix of cluster means, \mathbf{S}_{PW}, the per-stratum \mathbf{m}_s and \mathbf{C}_s, together with a scaled between covariance matrix based on Muthén’s scaling constant

s^{\ast} = \frac{N - \sum_j n_j^2 / N}{N_J - 1},

which equals the common cluster size when the design is balanced. This scaled matrix and the between covariance matrix derived from it reproduce the MUML (“Muthén’s limited information ML”) estimator of Muthén (1994), which is consistent for balanced data and approximate otherwise. lavaan does not use MUML for estimation (full ML is used throughout); these quantities serve only as easily computed starting values (see Section 16.7).

16.5.3 Between-only variables

When between-only variables \mathbf{z}_j (like w1 and w2) are present, the per-cluster likelihood is extended by treating (\mathbf{z}_j, \bar{\mathbf{y}}_j) as jointly normal: the between covariance matrix is partitioned into \boldsymbol{\Sigma}_{zz}, \boldsymbol{\Sigma}_{yz}, and the y-block of \boldsymbol{\Sigma}_B, and the code conditions the cluster means on \mathbf{z}_j via \boldsymbol{\Sigma}_{B \cdot z} = \boldsymbol{\Sigma}_B - \boldsymbol{\Sigma}_{yz} \boldsymbol{\Sigma}_{zz}^{-1} \boldsymbol{\Sigma}_{yz}^{\prime}, so that \boldsymbol{\Sigma}_{(s)} = \boldsymbol{\Sigma}_W + s\,\boldsymbol{\Sigma}_{B \cdot z} and the determinant splits as \log|\boldsymbol{\Sigma}_{zz}| + \log|\boldsymbol{\Sigma}_{(s)}|. The quadratic form in Equation 16.10 is assembled from the corresponding partitioned inverse. All these computations are carried out in a single loop over the cluster-size strata.

16.5.4 The objective function

The objective function that the optimizer minimizes is, as always in lavaan, sample-size independent. For two-level data it is

F_{2L}(\boldsymbol{\vartheta}) = \frac{-2 \log L(\boldsymbol{\vartheta})}{2N}, \tag{16.11}

where constants not involving the parameters are dropped. The gradient of Equation 16.11 is assembled by the chain rule: the derivative vector of -2\log L with respect to the moments is post-multiplied by the model Jacobian \boldsymbol{\Delta}= \partial \boldsymbol{\sigma}/ \partial \boldsymbol{\vartheta}^{\prime}, where the moment vector \boldsymbol{\sigma} stacks the within block (\boldsymbol{\mu}_W, \mathrm{vech}\,\boldsymbol{\Sigma}_W) on top of the between block (\boldsymbol{\mu}_B, \mathrm{vech}\,\boldsymbol{\Sigma}_B), and the result is divided by 2N. Note that, unlike the single-level ML case, F_{2L} is not a discrepancy between summary statistics and model-implied moments: there is no closed-form unrestricted solution to subtract. The comparison against an unrestricted model returns with the test statistic, which is why the \mathsf{H}_1 model needs to be estimated explicitly. That is the topic of the next section.

16.6 The unrestricted model

16.6.1 Why the unrestricted model must be estimated iteratively

In a single-level complete-data analysis, the unrestricted (\mathsf{H}_1) model has a closed-form solution: the sample mean and (ML) sample covariance matrix (Section 7.3.2). In the two-level case, the \mathsf{H}_1 model consists of the four blocks (\boldsymbol{\mu}_W, \boldsymbol{\Sigma}_W, \boldsymbol{\mu}_B, \boldsymbol{\Sigma}_B) without any structure, and, except in the balanced case, no closed-form ML solution exists: each cluster size weighs the two levels differently in Equation 16.8. The \mathsf{H}_1 solution is nevertheless needed in several places: for the likelihood-ratio test statistic, for fit indices, for the ICCs, and for starting values. lavaan therefore estimates the two-level \mathsf{H}_1 model iteratively, immediately after the sample statistics have been computed. The result is stored with the fitted object and can be inspected with lavInspect(fit, "h1").

16.6.2 The EM algorithm for the unrestricted model

For complete data, lavaan maximizes the \mathsf{H}_1 likelihood with an EM algorithm (Dempster et al., 1977) that treats the random intercepts \mathbf{y}_{B,j} as missing data (the algorithm is derived in appendix E.3). Given current values of the moments, the E-step computes, for every cluster, the posterior distribution of the between component given the observed cluster statistics. Absent between-only variables, this posterior is normal with mean

\mathrm{E}(\mathbf{y}_{B,j} \mid \text{data}) = \boldsymbol{\mu}_B + n_j \boldsymbol{\Sigma}_B \boldsymbol{\Sigma}_j^{-1} (\bar{\mathbf{y}}_j - \boldsymbol{\mu}), \tag{16.12}

and covariance matrix \boldsymbol{\Sigma}_B - n_j \boldsymbol{\Sigma}_B \boldsymbol{\Sigma}_j^{-1} \boldsymbol{\Sigma}_B (with \boldsymbol{\Sigma}_j = \boldsymbol{\Sigma}_W + n_j \boldsymbol{\Sigma}_B; when between-only variables are present, \mathbf{z}_j joins the conditioning set). From these posterior moments, the expected complete-data sums of squares are accumulated, again per cluster-size stratum, so the E-step cost is driven by the number of distinct sizes. The M-step is then trivial: with complete data, the ML estimates of the four blocks are ordinary means and covariance matrices of the (expected) within deviations and between components. Two refinements are worth noting:

  • the moments of the between-only block (\boldsymbol{\mu}_z and \boldsymbol{\Sigma}_{zz}) have a closed-form solution (the sample moments of the \mathbf{z}_j), and are computed once, outside the EM iterations;

  • within-level variances that collapse towards zero during the iterations are floored at the min_variance value (default 1e-05).

The EM iterations are accelerated by default using the SQUAREM scheme (Varadhan & Roland, 2008), which typically reduces the number of E/M cycles by an order of magnitude for slowly converging problems. Convergence is declared when the increase in the log-likelihood between cycles drops below a tolerance.

16.6.3 Options: em_h1_args

The EM run for the \mathsf{H}_1 model is controlled by the em_h1_args list option. The relevant elements (with their two-level defaults) are max_iter (5000), tol (1e-04; the log-likelihood increase), min_variance (1e-05), acceleration ("squarem"; alternatives "qn" and "none"), and non_pd_action / non_pd_tol, which govern what happens when the converged \hat{\boldsymbol{\Sigma}}_W or \hat{\boldsymbol{\Sigma}}_B is (near) singular (a warning by default). A near-singular \hat{\boldsymbol{\Sigma}}_B almost always signals that some shared variable has (essentially) no between-level variance; the warning names the variables concerned, and the remedy is usually to treat those variables as within-only. If the EM run reaches max_iter, a warning suggests increasing it:

fit <- sem(model, data = Demo.twolevel, cluster = "cluster",
           em_h1_args = list(max_iter = 20000L, tol = 1e-06))

(The tol element may be tightened at the same time; the default 1e-04 on the log-likelihood scale is accurate enough for test statistics, but a stricter tolerance can be useful when comparing log-likelihood values across software packages.)

The log-likelihood of the \mathsf{H}_1 solution is stored alongside the moments and is reported by fitMeasures() as unrestricted.logl:

fitMeasures(fit, c("logl", "unrestricted_logl", "npar", "aic", "bic"))
             logl unrestricted.logl              npar               aic 
        -12076.57         -12072.52             20.00          24193.13 
              bic 
         24309.61 

16.7 Estimating the model parameters

16.7.1 Quasi-Newton estimation and starting values

For complete data, the default optimizer is the quasi-Newton method of chapter 7 (see Section 7.1), minimizing Equation 16.11 with the analytic gradient described above; all the general facilities of that chapter (multiple attempts, bounds, optim_parscale, …) apply. Starting values deserve a comment, because the two-level case differs in one respect from the strategy of Section 6.1: the per-level \mathsf{H}_1 moments are already available when the starting values are computed, and lavaan uses them as if they were “sample statistics” for each level: residual variances start at a fraction of the \mathsf{H}_1 variances of the corresponding block, factor loadings are obtained from the usual instrumental-variables procedure applied to the \mathsf{H}_1 covariance matrix of that level, and the (fixed or free) moments of exogenous covariates are copied from the \mathsf{H}_1 solution directly. If the \mathsf{H}_1 computation was skipped (h1 = FALSE), the less accurate MUML-style moments of Section 16.5.2 are used instead.

A further option helps the optimizer: with optim_fix_saturated (current default TRUE), if an entire level is saturated, its parameters are temporarily fixed at their \mathsf{H}_1 values during optimization (they are the ML estimates of that block when no cross-level constraints exist) and released afterwards. This option is also respected by the EM optimizer of the next subsection: under the default optim_method = "em" for two-level models with missing = "ml", a fully saturated block is fixed at its \mathsf{H}_1 values from the first EM iteration onward. This is exact here because the M-step factorizes across levels, so a fully saturated model converges in a single EM iteration instead of many, at the same solution. (The random-slope EM is excluded.)

The automatic bounds of Section 6.2.2 (the bounds= argument) are also available for two-level models. They are computed for each level separately: where the single-level scheme uses the sample variances of the observed variables, the two-level scheme uses the within and the between variances of the \mathsf{H}_1 model (or, if the \mathsf{H}_1 computation was skipped, the MUML-style moments of Section 16.5.2). The between level needs wider bounds. The between variances of the \mathsf{H}_1 model are often estimated with little precision, and the model-implied between variances can be clearly larger, in particular if the intraclass correlations are small or the number of clusters is small. They are therefore multiplied by a factor before the upper bounds of the between-level parameters are computed. This factor is the upper_factor_between element of the optim_bounds list (current default 1.5). A between variance of the \mathsf{H}_1 model that is estimated to be negative is treated as zero. Automatic bounds are not available for models with random slopes in version 0.7-4: lavaan gives a warning, and the model is fitted without them.

16.7.2 EM estimation of the user-specified model

The structural model itself can also be estimated with an EM algorithm by setting optim_method = "em". For two-level models with missing = "ml", EM is even the default optimizer, because it is considerably more robust in that setting; if the EM implementation does not support a particular model (e.g., multiple groups, or conditional_x = TRUE), lavaan silently falls back to the default quasi-Newton optimizer.

The \mathsf{H}_0 EM algorithm has a simple structure. The E-step is identical to the \mathsf{H}_1 E-step: given the current model-implied moments, compute the expected complete-data moments (\tilde{\boldsymbol{\mu}}_W, \tilde{\boldsymbol{\Sigma}}_W, \tilde{\boldsymbol{\mu}}_B, \tilde{\boldsymbol{\Sigma}}_B). The M-step then maximizes the expected complete-data log-likelihood. For a structured model, this is itself a small SEM problem: the complete-data likelihood factors into two independent normal samples (the within deviations and the between components), so the M-step amounts to fitting a two-group model, with the within model as “group 1” (sample size N) and the between model as “group 2” (sample size N_J), to the expected moments. lavaan does exactly this: the parameter table is relabeled (the level column becomes a group column), and a standard complete-data ML fit is run on sample_cov = list(within = ..., between = ...). Cross-level equality constraints survive this relabeling unchanged, which is why the EM route supports them without any additional provisions.

The EM iterations stop when the change in the log-likelihood falls below em_args$fx_tol or the parameter changes fall below em_args$dx_tol; they are SQUAREM-accelerated by default; and variances fixed to exact zero are replaced by the small em_args$zerovar_offset (1e-04) during the iterations, since EM cannot handle exact zeros. The stopping rules of the EM cycles are absolute criteria, and EM often stalls when the log-likelihood flattens before the gradient has fully converged, so that the EM solution may still be slightly inaccurate. The default em_args$nlminb_handoff = TRUE therefore always completes the optimization with a quasi-Newton run started from the EM solution (accepted only if its solution is at least as good), and the final solution meets the same convergence criteria as a solution found by the quasi-Newton optimizer alone. The default quasi-Newton optimizer and optim_method = "em" then arrive at the same solution for all practical purposes:

fit_em <- sem(model, data = Demo.twolevel, cluster = "cluster",
              optim_method = "em")
max(abs(coef(fit_em) - coef(fit)))
[1] 0.0001065637

16.7.3 Convergence tips

Two-level models fail to converge more often than single-level models, almost always because of the between level. Points to check, roughly in order:

  1. ICCs: shared variables with very small ICCs (say, below .05) carry almost no between-level information; their between (residual) variances are weakly identified and tend to drift to zero or below. Consider treating such variables as within-only, or fixing their between residual variances to zero.

  2. The \mathsf{H}_1 warnings: a “(near) zero variance at between level” or near-singular \hat{\boldsymbol{\Sigma}}_B warning from the \mathsf{H}_1 step predicts convergence problems for any between model that assigns those variables free variances.

  3. Cluster sizes: with very small average cluster sizes (say, below 2), the within/between decomposition itself is barely identified; lavaan warns when the average cluster size drops below 1.5.

  4. Try optim_method = "em". The EM algorithm approaches the optimum from the interior of the parameter space and is much less sensitive to the large intermediate steps that can cause a quasi-Newton run to fail. Its variance floor (zerovar_offset) also keeps the iterates away from the boundary of the parameter space.

  5. Saturate a level. If a model with a saturated between level converges but the full model does not, the between model is the cause; simplify it (fewer free between variances, cross-level equality constraints on loadings) and refit.

16.8 Standard errors and test statistics

16.8.1 Information matrices

All standard errors for two-level ML estimation derive from the information matrices of Section 8.2, in their multilevel versions described in Section 8.2.4. To recapitulate briefly, in terms of the quantities of this chapter:

  • the expected information is assembled per cluster-size stratum: each stratum contributes the expected Hessian of Equation 16.10, and the within part contributes (N - N_J) copies of the standard normal-theory information evaluated at \boldsymbol{\Sigma}_W; the \mathsf{H}_0 version projects the blocks through the model Jacobian level by level, because the two levels enter with different weights and cannot be projected through a single global triple product;

  • the observed information is the numerically differentiated analytic gradient of Equation 16.11 (Richardson extrapolation), multiplied by N / N_J so that it is expressed per cluster as well; with missing data, it is instead computed analytically by Louis’s method, for the \mathsf{H}_0 and the \mathsf{H}_1 versions alike (see Section 16.9 and appendix E.5);

  • the first-order information treats the clusters as the independent units: lavaan computes one score row per cluster (chained through \boldsymbol{\Delta}) and averages their outer products over the N_J clusters.

For two-level models, the default is information = "observed" (for both standard errors and the test), rather than the single-level default "expected". Note the unit convention: all three matrices are expressed per cluster (the total information divided by N_J), and, correspondingly, vcov() inverts the unit information and divides by N_J, not by N as a casual reading of Equation 8.25 might suggest. The cluster bootstrap uses the same denominator, so that bootstrap and information-based standard errors are on the same scale.

16.8.2 Standard errors

Three options for the se argument are available in the two-level ML setting:

  • se = "standard" (the default with estimator = "ML"): the inverse of the (observed, by default) unit information matrix, divided by N_J.

  • se = "robust.huber.white" (the default with estimator = "MLR"; alias "sandwich"): the sandwich estimator of Equation 8.28, where the meat is the first-order information built from the cluster-wise scores. This protects against non-normality of both the within and the between components. There is no "robust.sem"-style alternative for two-level ML models (the two-level sandwich estimator of \hat{\boldsymbol{\Gamma}} described in Section 16.11.1 serves the least-squares estimators and the residual-based tests of Section 16.8.3, not the ML standard errors), and se = "robust.cluster" does not apply, because the model already accounts for the clustering.

  • se = "bootstrap": nonparametric bootstrap, resampling clusters (with their entire contents) rather than individual observations. The cluster bootstrap is also available with missing data (missing = "ml"; see Section 16.9).

fit_mlr <- sem(model, data = Demo.twolevel, cluster = "cluster",
               estimator = "MLR")

The cluster-wise scores themselves are returned by lavScores() (Section 9.10.2). In a single-level model this function returns one row per observation; for a two-level model it returns one row per cluster, since the clusters are the independent units: row j is the derivative of \log L_j with respect to the free parameters, and the columns sum to zero at the solution (up to the convergence tolerance).

sc <- lavScores(fit)
dim(sc)
[1] 200  20

With these scores, the sandwich estimator can be computed by hand. The bread is the inverse of the observed information of the total log-likelihood, which is what vcov() returns for the fit with se = "standard", and the meat is the cross-product of the scores:

vcov_hw <- vcov(fit) %*% crossprod(sc) %*% vcov(fit)
cbind(by_hand = sqrt(diag(vcov_hw)),
      MLR = sqrt(diag(vcov(fit_mlr))))[1:5, ]
          by_hand        MLR
fw=~y2 0.03709730 0.03709730
fw=~y3 0.03323725 0.03323725
fw~x1  0.02348161 0.02348161
fw~x2  0.02270565 0.02270565
fw~x3  0.01760710 0.01760710

The scores are also the input for other tools that work with estimating functions, written by the user or provided by other packages. In version 0.7-4, two-level scores are available for ML, with complete or missing data, but not with conditional_x = TRUE and not for models with random slopes. With cluster sampling weights (Section 16.10), each row is multiplied by the weight of its cluster.

16.8.3 Test statistics

Because the objective function Equation 16.11 is not a discrepancy with a known minimum of zero, the standard chi-square statistic cannot be computed as N times the minimized fit function value. Instead, lavaan computes a genuine likelihood-ratio statistic against the \mathsf{H}_1 model of Section 16.6:

X^2 = -2\,\bigl[\log L(\hat{\boldsymbol{\vartheta}}) - \log L_{\mathsf{H}_1}\bigr], \tag{16.13}

with degrees of freedom equal to the number of free \mathsf{H}_1 moments (per level, after removing the fixed-x moments and the structurally-zero within means of shared variables) minus the number of free model parameters. For the running example: the \mathsf{H}_1 model counts 3 + 21 = 24 within moments (3 means of the within-only variables plus \mathrm{vech} of a 6 \times 6 matrix) and 5 + 15 = 20 between moments, of which 9 within and 5 between moments involve only fixed exogenous covariates, leaving 30; with 20 free parameters, df = 10:

fitMeasures(fit, c("chisq", "df", "pvalue"))
 chisq     df pvalue 
 8.092 10.000  0.620 

As for single-level ML (Section 8.5.10), the default test= for a two-level ML model adds Browne’s residual-based test in its normal-theory model-based version, browne.residual.nt.model (with missing = "ml", the sample-based version browne.residual.nt is added instead); this is the second block of the summary() output shown in Section 16.4.1. Its residual is the difference between the \mathsf{H}_1 moments of Section 16.6 and the model-implied moments at both levels, and the weight matrix is the per-cluster \mathsf{H}_1 information of Section 16.8.1 evaluated at the model-implied moments, so that the number of clusters N_J plays the role of the sample size. The other three variants (the sample-based normal-theory version, and the two ADF versions built on the two-level sandwich estimator of \hat{\boldsymbol{\Gamma}}) can be requested explicitly, also post hoc with lavTest(), for complete and for incomplete data. The details, including the treatment of fixed exogenous covariates and of equality constraints, are given in Section 8.5.10. All four variants are also available with conditional_x = TRUE (Section 16.4.6), and a normal-theory version is again part of the default. The residual is then defined in terms of the conditional statistics of each level (the residual intercepts, the slopes, and the residual covariances), obtained from the \mathsf{H}_1 moments on the one hand and from the model on the other. The resulting values are close, but not identical, to those of the same model fitted with conditional_x = FALSE.

lavTest(fit, test = c("browne.residual.nt", "browne.residual.adf",
                      "browne.residual.adf.model"), output = "text")
Model Test User Model:
                                                      
  Test statistic                                 8.092
  Degrees of freedom                                10
  P-value (Chi-square)                           0.620
                                                      
  Browne's residual-based (NT) test                   
  Test statistic                                 8.071
  Degrees of freedom                                10
  P-value (Chi-square)                           0.622
                                                      
  Browne's residual-based (ADF) test                  
  Test statistic                                 7.895
  Degrees of freedom                                10
  P-value (Chi-square)                           0.639
                                                      
  Browne's residual (ADF model-based) test            
  Test statistic                                 6.976
  Degrees of freedom                                10
  P-value (Chi-square)                           0.728

For robust inference, the scaled versions of the test are available: test = "yuan.bentler" and test = "yuan.bentler.mplus" (the default with estimator = "MLR"; see Section 8.5.5). These are the only scaled tests for two-level ML: the Satorra–Bentler family (test = "satorra.bentler", "scaled.shifted", "mean.var.adjusted") requires a sample-based \hat{\boldsymbol{\Gamma}} and is not available (requesting it produces an error); it is, however, the default for the robust variants of the two-level least-squares estimators of Section 16.11.1 (for example WLSMV). The ingredients of the Yuan–Bentler scaling factor (Equation 8.45) are the multilevel information matrices described above, the first-order information from the cluster-wise scores and the (observed, by default) information, evaluated at both the \mathsf{H}_0 and the \mathsf{H}_1 solutions:

fitMeasures(fit_mlr, c("chisq_scaled", "df_scaled", "pvalue_scaled",
                       "chisq_scaling_factor"))
        chisq.scaled            df.scaled        pvalue.scaled 
               8.351               10.000                0.595 
chisq.scaling.factor 
               0.969 

Nested two-level models can be compared with lavTestLRT() as usual, including the appropriate scaled difference tests when estimator = "MLR" is used (see Section 11.2.4).

16.9 Missing data

With missing = "ml", lavaan maximizes the observed-data log-likelihood of the two-level model: for each cluster, the missing entries of the data matrix are integrated out of the joint normal distribution implied by Equation 16.5. The observed-data likelihood no longer reduces to the sufficient statistics of Section 16.5.2, because the pattern of missingness interacts with the cluster structure, but it can still be evaluated cluster by cluster using P \times P building blocks; the derivation, from formulas down to R code, is given in Rosseel (2021). The option conditional_x = TRUE is not supported in this setting, but sampling weights at both levels are (Section 16.10).

Three design choices make the two-level FIML route fast and robust:

  • EM for the \mathsf{H}_1 model: the unrestricted model with missing data is estimated by an EM algorithm whose E-step integrates over both the random intercepts and the missing values (derived in appendix E.4). The alternative (a Cholesky-parameterized quasi-Newton fit of the unrestricted model) remains available via h1_missing_method = "fiml".

  • EM as the default optimizer for the \mathsf{H}_0 model: as mentioned in Section 16.7.2, optim_method = "em" is the default when missing = "ml" is combined with a two-level model. The E-step code is shared with the \mathsf{H}_1 EM.

  • Louis’s method for the observed information: instead of numerically differentiating the (computationally demanding) missing-data gradient (4 \times T full-data passes, where T is the number of free parameters), the observed information is computed analytically in a single pass using Louis’s identity (Louis, 1982), which is worked out for the two-level model in appendix E.5: the observed-data information equals the expected complete-data information minus the posterior variance of the complete-data score. Treating the random intercepts, the missing responses, and the missing between-only values as the “complete” data, the complete-data model is again the two-group model of Section 16.7.2, so the first term needs only one E-step; the second term is computed in closed form from the posterior distribution of the cluster-level unknowns. The same identity, applied to the unrestricted moments instead of the model parameters, gives the observed information of the \mathsf{H}_1 model that the scaled test statistics need. If the computation fails for a particular model, lavaan silently falls back to numerical differentiation.

No special syntax is needed, and robust (MLR) inference can be combined with missing data without any additional settings. The other tools of Section 16.8.2 carry over as well: lavScores() returns the cluster-wise scores of the observed-data log-likelihood, and the cluster bootstrap (se = "bootstrap", or the bootstrapLavaan() function) resamples whole clusters together with their missing values.

set.seed(123)
d <- Demo.twolevel
d$y1[sample(nrow(d), 200)] <- NA
d$y2[sample(nrow(d), 200)] <- NA
fit_miss <- sem(model, data = d, cluster = "cluster",
                missing = "ml", estimator = "MLR")
fitMeasures(fit_miss, c("chisq_scaled", "df_scaled", "pvalue_scaled"))
 chisq.scaled     df.scaled pvalue.scaled 
        8.549        10.000         0.575 

16.10 Sampling weights

In many large-scale surveys, the data are collected in two stages: clusters (schools) are sampled first, and units (students) are sampled within the selected clusters, with unequal selection probabilities at one or both stages. If these probabilities are related to the outcomes, even after conditioning on the covariates of the model, the unweighted estimates are biased, and sampling weights (the inverses of the selection probabilities) are needed. In a single-level analysis there is one weight per case (Section 5.1.8). In a two-level model, one weight per case is not enough, because the two stages of the design correspond to the two levels of the model, and each level needs its own weight (Pfeffermann et al., 1998):

  • the cluster weight w_j is the inverse of the probability that cluster j was selected. It is given by the sampling_weights_cluster= argument, which names a variable that is constant within each cluster;

  • the level-1 weight w_{i \mid j} is the inverse of the probability that unit i was selected, given that its cluster was selected. It is given by the sampling_weights= argument.

Either argument can be used without the other. All weights must be strictly positive. Many datasets only provide an overall weight for each unit, which is the product w_j\, w_{i \mid j}; such a weight cannot be used as a level-1 weight as it stands, and must first be divided by the cluster weight.

The weights enter the estimation as follows (Asparouhov, 2006; Rabe-Hesketh & Skrondal, 2006). Write f(\mathbf{y}_{ji} \mid \mathbf{u}_j) for the density of the data of unit i given the random effects \mathbf{u}_j of its cluster, and g(\mathbf{u}_j) for the density of the random effects. The weighted contribution of cluster j and the function that is maximized are

\log L_j^{w} = \log \int \prod_{i=1}^{n_j} f(\mathbf{y}_{ji} \mid \mathbf{u}_j)^{\,w_{i \mid j}}\; g(\mathbf{u}_j)\, d\mathbf{u}_j, \qquad \log L^{w}(\boldsymbol{\vartheta}) = \sum_{j=1}^{N_J} w_j\, \log L_j^{w}. \tag{16.14}

Each unit counts w_{i \mid j} times within its cluster, and each cluster counts w_j times. This is not the likelihood of the observed data, but a (multilevel) pseudo-likelihood: an estimate of the log-likelihood that would have been obtained if the whole population had been observed. For the normal two-level model, the integral is again available in closed form, and the result has the same form as Equation 16.8: the cluster size n_j is replaced by the sum of the level-1 weights of the cluster, \tilde{n}_j = \sum_i w_{i \mid j}, the cluster mean \bar{\mathbf{y}}_j by the weighted cluster mean, and the within-cluster scatter matrix \mathbf{A}_j by its weighted version. The cluster weights then multiply the contributions of the clusters, in the log-likelihood, in the gradient, and in the EM algorithms for the unrestricted and the fitted model.

Before they are used, the weights are rescaled, and here the two levels behave very differently. Multiplying all the cluster weights by a constant has no effect on the estimates. By default, they are rescaled so that the implied weights of the level-1 units (the cluster weight times the level-1 weight, or the cluster weight alone if there are no level-1 weights) sum to the number of observations, per group; this is governed by the sampling_weights_normalization option, as in the single-level case. The scale of the level-1 weights, in contrast, does matter: since \tilde{n}_j takes the place of the cluster size, it determines how precisely a cluster mean is assumed to be measured, and therefore how the variance of the cluster means is divided into a within and a between part. Raw weights (which sum to the size of the cluster in the population) would make every cluster look very large, and the between-level variances would be overestimated. The level-1 weights are therefore rescaled within each cluster, as determined by the sampling_weights_scaling option:

  • "cluster" (the default): the weights of a cluster sum to the cluster size n_j;

  • "ecluster": they sum to the effective cluster size, (\sum_i w_{i \mid j})^2 / \sum_i w_{i \mid j}^2, which is smaller than n_j when the weights within a cluster are unequal;

  • "none": the weights are used as they are.

These are the two scaling methods of Pfeffermann et al. (1998), and the three settings correspond to the WTSCALE option of Mplus. No scaling method removes the bias of the variance components completely when the clusters are small and the level-1 weights are informative; the bias vanishes as the cluster sizes increase (Asparouhov, 2006; Rabe-Hesketh & Skrondal, 2006). When the level-1 weights are constant within every cluster, the first two settings reduce them to one, and the weights have no effect.

As an illustration, we add two (artificial) weight variables to the Demo.twolevel data, and refit the model of Section 16.4.1:

set.seed(1234)
Demo_wt <- Demo.twolevel
n_clus <- length(unique(Demo_wt$cluster))
Demo_wt$wt2 <- runif(n_clus, min = 1, max = 4)[Demo_wt$cluster]
Demo_wt$wt1 <- runif(nrow(Demo_wt), min = 1, max = 3)
fit_wt <- sem(model, data = Demo_wt, cluster = "cluster",
              sampling_weights = "wt1",
              sampling_weights_cluster = "wt2")
fit_wt
lavaan 0.7-4 ended normally after 37 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        20

  Number of observations                          2500
  Number of clusters [cluster]                     200
  Sampling weights variable                        wt1
  Sampling weights scaling                     cluster
  Cluster sampling weights variable                wt2

Model Test User Model:
                                              Standard      Scaled
  Test Statistic                                 7.339       6.288
  Degrees of freedom                                10          10
  P-value (Chi-square)                           0.693       0.790
  Scaling correction factor                                  1.167
    Yuan-Bentler correction (Mplus variant)                       

The header lists the two weight variables and the scaling of the level-1 weights. Since the pseudo-likelihood is not a likelihood, the standard errors and the test statistic that are based on the information matrix alone are not valid. With sampling weights at either level, the defaults therefore switch to se = "robust.huber.white" and test = "yuan.bentler.mplus": the sandwich estimator of Section 16.8.2, with the weighted cluster-wise scores in its meat, and the scaled test statistic that is derived from it. The log-likelihood and the information criteria are still reported, but they refer to the pseudo-likelihood. In this example the weights were generated independently of the data, so they are not informative, and the estimates are close to the unweighted ones:

round(cbind(unweighted = coef(fit), weighted = coef(fit_wt))[1:9, ], 3)
       unweighted weighted
fw=~y2      0.774    0.761
fw=~y3      0.734    0.718
fw~x1       0.510    0.503
fw~x2       0.407    0.402
fw~x3       0.205    0.196
y1~~y1      0.986    0.954
y2~~y2      1.066    1.053
y3~~y3      1.011    1.014
fw~~fw      0.546    0.544

Sampling weights can be combined with missing data. With missing = "ml", the level-1 weight of a unit multiplies the log-likelihood contribution of its observed values (given the random effects of its cluster), and the cluster weights are used as before:

set.seed(123)
Demo_wt$y1[sample(nrow(Demo_wt), 200)] <- NA
fit_wt_miss <- sem(model, data = Demo_wt, cluster = "cluster",
                   sampling_weights = "wt1",
                   sampling_weights_cluster = "wt2", missing = "ml")
fitMeasures(fit_wt_miss, c("chisq_scaled", "df_scaled", "pvalue_scaled"))
 chisq.scaled     df.scaled pvalue.scaled 
        6.692        10.000         0.754 

With level-1 weights and missing data, the observed information matrix is obtained by numerical differentiation (the analytic route of Section 16.9 is only available without level-1 weights), which makes this combination slower.

In version 0.7-4, sampling weights in a two-level model are available for continuous data, with estimator = "ML" (or "MLR") and with the least-squares estimators WLS, DWLS and ULS (and their robust variants; see Section 16.11.1), where the weights are used in the unrestricted statistics and in their asymptotic covariance matrix. They are not available for estimator = "GLS" (its normal-theory weight matrix ignores the weights), for categorical data, with conditional_x = TRUE, or for models with random slopes (Section 16.13). Missing data can only be combined with sampling weights when missing = "ml" is used with ML.

16.11 Two-level SEM with categorical data

Combining the two-level model of this chapter with the categorical methods of chapter 14 is computationally demanding. A full-information ML approach would have to integrate the likelihood over the latent responses of every observation in a cluster jointly, an integral whose dimension grows with the cluster size, and this is not implemented in lavaan. Requesting it produces an error message:

multilevel + categorical data is only supported for the (D)WLS/ULS estimators (e.g., WLSMV) (for now).

What is implemented is a limited-information alternative: the two-level model is fitted by least squares to a vector of unrestricted two-level statistics. For categorical (and mixed) endogenous variables, this is the only way to fit a two-level model in lavaan (as of version 0.7-4). We first describe the least-squares route for continuous data, where the unrestricted statistics are those of Section 16.6, and then the stage-wise procedure that provides them for categorical data.

16.11.1 Two-level least-squares estimation

The least-squares family (GLS, WLS, DWLS, ULS, and the robust variants of the last three) can be used for two-level models with complete data, and all of them except GLS can be combined with sampling weights (Section 16.10). The general framework is the one of Section 7.4: a vector of unrestricted “sample statistics”, a weight matrix, and a model Jacobian. For continuous data, the unrestricted statistic vector is the two-level \mathsf{H}_1 estimate itself, \mathbf{s}= (\hat{\boldsymbol{\mu}}_W, \mathrm{vech}\,\hat{\boldsymbol{\Sigma}}_W, \hat{\boldsymbol{\mu}}_B, \mathrm{vech}\,\hat{\boldsymbol{\Sigma}}_B), and its asymptotic covariance matrix treats the clusters as the independent units (a sandwich built from the cluster-wise \mathsf{H}_1 scores). The inverse of this matrix is the weight matrix of the WLS estimator (its diagonal for DWLS), so that these estimators are of the asymptotically distribution-free type.

With estimator = "GLS", the same statistic vector is used, but the weight matrix is the normal-theory one: the expected information matrix of the unrestricted two-level model, evaluated at the \mathsf{H}_1 estimates. This is the weight matrix of the sample-based normal-theory version of Browne’s residual-based test (Section 16.8.3), and it is the two-level counterpart of the single-level GLS estimator of Section 7.4.4, where the weight matrix is built from the sample covariance matrix. As in the single-level case, standard errors and the test statistic are the standard (normal-theory) ones by default. GLS is available for continuous data only; the stage-wise statistics for categorical data described next have no normal-theory weight matrix.

For categorical (and mixed) endogenous variables, an unrestricted two-level model cannot be estimated in this way, and the statistic vector is obtained in stages.

16.11.2 The unrestricted statistics for categorical data

For categorical data, lavaan follows the approach introduced in Mplus (Asparouhov & Muthén, 2007): a two-level version of the three-stage WLSMV pipeline of Section 14.4, in which the unrestricted (\mathsf{H}_1) statistics are estimated stage-wise, so that no integral ever has more than a few dimensions:

  1. Univariate two-level models, one per variable: for an ordinal variable, a two-level probit model is maximized by Gauss–Hermite quadrature over the cluster-level (between) component, yielding the thresholds and the between-level variance of its latent response; the within-level residual variance of y^* is fixed to one, which is why only parameterization = "Theta" (Section 14.5.2) is available. Continuous variables get their mean and within/between variances; mixed models are handled in the same way.

  2. Bivariate two-level models, one per pair: with the univariate parameters held fixed, each pair of variables yields a small two-level model for two parameters: the within and between residual covariances (c_W, c_B) of the pair, the two-level analogue of the polychoric correlation, split by level. Depending on the pair type (ordinal/ordinal, continuous/ordinal, continuous/continuous), a dedicated two-dimensional fitter is used.

  3. A stage-wise sandwich for the joint uncertainty: the asymptotic covariance matrix of the full statistic vector (thresholds and between-variances per variable, then (c_W, c_B) per pair) is assembled from the cluster-wise scores (the clusters are the independent units), with a triangular-system correction that propagates the stage-1 uncertainty into the stage-2 estimates, exactly as the single-level three-step procedure does across its steps (Section 14.4.3). The sample-statistics code and the model-implied counterpart (and its Jacobian) are mapped in Table 16.1.

16.11.3 Fitting the model

The model is then fitted to this statistic vector by diagonally weighted least squares, and the defaults mirror the single-level WLSMV conventions: se = "robust.sem" sandwich standard errors, with the observed information as the bread of the sandwich, just as in the single-level case (Section 14.5.6; information_bread = "expected" restores the expected bread), and a scaled-and-shifted test statistic. A small simulated example follows: a single construct measured by four three-category items at both levels.

pop_2lcat <- '
level: 1
  fw =~ 0.8*y1 + 0.7*y2 + 0.6*y3 + 0.8*y4
  fw ~~ 1.0*fw
  y1 | -0.8*t1 + 0.8*t2
  y2 | -0.6*t1 + 1.0*t2
  y3 | -1.0*t1 + 0.5*t2
  y4 | -0.7*t1 + 0.7*t2
level: 2
  fb =~ 0.7*y1 + 0.6*y2 + 0.7*y3 + 0.5*y4
  fb ~~ 0.3*fb
  y1 ~~ 0.1*y1
  y2 ~~ 0.1*y2
  y3 ~~ 0.1*y3
  y4 ~~ 0.1*y4
'
Data2l <- lavSimulateData(pop_2lcat, sample_nobs = 3000,
                       cluster_idx = rep(1:150, each = 20), seed = 123)

model_2lcat <- '
level: 1
  fw =~ y1 + y2 + y3 + y4
level: 2
  fb =~ y1 + y2 + y3 + y4
'
fit_2lcat <- sem(model_2lcat, data = Data2l, cluster = "cluster",
                 ordered = paste0("y", 1:4), estimator = "WLSMV")
fitMeasures(fit_2lcat, c("chisq_scaled", "df_scaled", "pvalue_scaled",
                         "cfi_scaled", "rmsea_scaled", "srmr"))
 chisq.scaled     df.scaled pvalue.scaled    cfi.scaled  rmsea.scaled 
        2.542         4.000         0.637         1.000         0.000 
         srmr 
        0.033 
pe <- parameterEstimates(fit_2lcat)
pe[pe$op == "=~", c("lhs", "op", "rhs", "level", "est", "se")]
   lhs op rhs level   est    se
1   fw =~  y1     1 1.000 0.000
2   fw =~  y2     1 0.816 0.082
3   fw =~  y3     1 0.674 0.059
4   fw =~  y4     1 1.000 0.096
27  fb =~  y1     2 1.000 0.000
28  fb =~  y2     2 0.742 0.145
29  fb =~  y3     2 1.092 0.192
30  fb =~  y4     2 0.477 0.126

Despite the repeated quadrature in the stage-wise estimation, the whole analysis takes well under a second: the integrals are at most two-dimensional, and their number grows only linearly (stage 1) and quadratically (stage 2) in the number of variables, never with the cluster size. The implementation closely follows Mplus (TYPE = TWOLEVEL with WLSMV) for factor models, regressions, and covariate extensions.

Some practical limitations apply in version 0.7-4. Exogenous covariates are supported, with both fixed_x = TRUE and conditional_x = TRUE: within-level covariates enter the (probit) regressions of every variable, between-level covariates only those of variables with a between part. The data must be complete: incomplete cases are removed listwise, and there is no two-level analogue of missing = "pairwise". Finally, only parameterization = "Theta" is available, as explained above.

16.12 Inspecting a two-level model fit

16.12.1 Per-level quantities via lavInspect

Most lavInspect() keys (see Section 9.12) return, for a two-level model, a list with one element per level. The element names do not come from the labels in the model syntax: by default, the first element is called within and the second is named after the cluster variable (here, cluster); the level_label argument can be used to override them. The most useful keys:

lavInspect(fit, "implied")   # model-implied moments per level
lavInspect(fit, "h1")        # unrestricted (EM) moments per level
lavInspect(fit, "sampstat")  # same as "h1" for two-level models
lavInspect(fit, "cov_lv")    # latent covariances per level
lavInspect(fit, "est")       # model matrices per level

Clustering-related keys return scalars or vectors:

lavInspect(fit, "nclusters")            # number of clusters (J)
[1] 200
lavInspect(fit, "average_cluster_size") # average cluster size
[1] 12.48744
lavInspect(fit, "icc")
   y1    y2    y3    x1    x2    x3 
0.331 0.263 0.232 0.000 0.000 0.000 

The ICCs are computed from the \mathsf{H}_1 solution via Equation 16.6; within-only variables have an ICC of zero by construction. In the example, roughly a quarter to a third of the variance of y1–y3 is between-cluster variance, which is too large to be ignored.

A related key is lavInspect(fit, "ranef"): the estimated random effects (the posterior means Equation 16.12 of the between components, evaluated at the final estimates), one row per cluster. This is the two-level analogue of lme4::ranef(). Factor scores for latent variables are obtained per level with lavPredict(fit) (within factors; one row per observation) and lavPredict(fit, level = 2L) (between factors; one row per cluster); see Section 13.3.10.

16.12.2 Residuals and fit measures per level

fitted() returns the implied moments per level, and residuals() / lavResiduals() compare them against the \mathsf{H}_1 moments, again per level; all the standardization methods of Section 10.8 apply blockwise:

lavResiduals(fit)$cluster$summary
                           cov     mean  total
srmr                     0.034    0.000  0.029
srmr.se                  0.008    0.000  0.007
srmr.exactfit.z          1.459    0.000  1.459
srmr.exactfit.pvalue     0.072    0.500  0.072
usrmr                    0.027    0.000  0.024
usrmr.se                 0.016    0.000  0.014
usrmr.ci.lower           0.001    0.000  0.001
usrmr.ci.upper           0.054    0.000  0.046
usrmr.closefit.h0.value  0.050    0.050  0.050
usrmr.closefit.z        -1.419 -744.802 -1.903
usrmr.closefit.pvalue    0.922    1.000  0.971

Global fit measures (CFI, RMSEA, SRMR, …) are computed from the pooled test statistic and are dominated by the within level, which is estimated from far more information; a badly misspecified between model can go undetected when the within model fits well (Ryu & West, 2009). Two remedies are available and are discussed in detail in chapter 10: level-specific SRMR values (srmr_within, srmr_between; see Section 10.5) and level-specific fit measures based on partially saturated models, via fitMeasures(fit, level = ) (Section 10.7):

fitMeasures(fit, c("cfi", "rmsea", "srmr_within", "srmr_between"))
         cfi        rmsea  srmr_within srmr_between 
       1.000        0.000        0.004        0.034 
fitMeasures(fit, c("chisq", "df", "pvalue"), level = "between")
Fit measures for the between level only (the other level is saturated):

 chisq     df pvalue 
 6.656  4.000  0.155 

16.13 Random slopes

In the random-intercept model, the clusters differ in their level only: the between component \mathbf{y}_{B,j} shifts the intercepts of the within model, but the within model itself (its loadings, its regression coefficients) is the same in every cluster. In the mixed-model tradition, the regression coefficients may vary across clusters as well: a random slope is a regression coefficient with a distribution. lavaan offers random slopes through the rv() modifier, for regressions among observed and latent variables alike. A two-level regression with random slopes then gives the same results as a linear mixed model fitted with, say, the lme4 package (Bates et al., 2015), but the slopes can also be attached to latent variables, be predicted by cluster-level variables, or predict them in turn.

This section first presents the syntax, by means of a model that every user of mixed models knows. It then explains why random slopes change the nature of the likelihood, how they are represented in the model matrices, which likelihood is maximized, and what this implies for estimation and inference. The approach follows Rockwood (2020); the computational details (the reduction to per-cluster cross-products, the analytic gradient, the EM algorithm, the quadrature for latent covariates) are given in appendix E.7.

16.13.1 From the mixed model to the rv() modifier

The sleepstudy data of the lme4 package contain the average reaction time (Reaction, in milliseconds) of 18 subjects on ten consecutive days (Days) of sleep deprivation. The standard analysis is a linear growth model in which both the intercept and the slope of Days vary across subjects:

data(sleepstudy, package = "lme4")
fit_lmer <- lme4::lmer(Reaction ~ Days + (Days | Subject),
                       data = sleepstudy, REML = FALSE,
                       control = lme4::lmerControl(optimizer = "bobyqa"))
print(fit_lmer)
Linear mixed model fit by maximum likelihood  ['lmerMod']
Formula: Reaction ~ Days + (Days | Subject)
   Data: sleepstudy
      AIC       BIC    logLik -2*log(L)  df.resid 
1763.9393 1783.0971 -875.9697 1751.9393       174 
Random effects:
 Groups   Name        Std.Dev. Corr 
 Subject  (Intercept) 23.781        
          Days         5.717   0.08 
 Residual             25.592        
Number of obs: 180, groups:  Subject, 18
Fixed Effects:
(Intercept)         Days  
     251.41        10.47  

We set REML = FALSE because lavaan provides (full) maximum likelihood estimates only. The control= argument selects another optimizer than the default one of lme4. This is not needed for the analysis itself, but the log-likelihood of this model is very flat around its maximum, and the default optimizer stops a little earlier: the variance components would differ from those below in the second decimal. In lavaan, the same model is a two-level model in which the occasions are the level-1 units and the subjects are the clusters:

model_ss <- '
  level: 1
    Reaction ~ rv("slope")*Days
  level: 2
    Reaction ~~ Reaction
'
fit_ss <- sem(model_ss, data = sleepstudy, cluster = "Subject")
parameterEstimates(fit_ss, ci = FALSE)
        lhs op      rhs block level     est      se      z pvalue
1  Reaction  ~     Days     1     1   0.000   0.000     NA     NA
2  Reaction ~~ Reaction     1     1 654.941  77.185  8.485  0.000
3      Days ~~     Days     1     1   8.250   0.000     NA     NA
4  Reaction ~1              1     1   0.000   0.000     NA     NA
5      Days ~1              1     1   4.500   0.000     NA     NA
6  Reaction ~~ Reaction     2     2 565.514 265.265  2.132  0.033
8     slope ~~    slope     2     2  32.682  13.573  2.408  0.016
9     slope ~~ Reaction     2     2  11.056  42.876  0.258  0.797
10 Reaction ~1              2     2 251.405   6.632 37.906  0.000
11    slope ~1              2     2  10.467   1.502  6.968  0.000

In the within block, the rv() modifier is placed in front of the covariate, where a fixed coefficient or a label would otherwise stand. It declares that the regression coefficient of Reaction on Days is not a parameter but a random variable. The (quoted) argument of rv() gives this variable a name, and under that name it becomes a latent variable in the between block. Everything that would be said about the slope in a mixed model is said in the between block, in terms of this latent variable:

  • its intercept (slope ~ 1) is the mean of the slopes over the clusters, which is the fixed effect of Days in the mixed model;

  • its variance (slope ~~ slope) is the slope variance;

  • its covariance with the between component of Reaction (slope ~~ Reaction) is the covariance between the random intercept and the random slope;

  • a regression on a cluster-level covariate (slope ~ w) is a cross-level interaction (the term Days:w of the mixed model).

The intercept and the variance of a random slope are added automatically as free parameters, and so is, in the sem(), cfa() and growth() functions, its covariance with the random intercept. As in lme4, where all the random effects of a term are correlated, a random slope is by default correlated with the other random effects of the between level. The rules, and the reason for this default, are given in Section 16.13.2. The random intercept needs no special syntax, but Reaction must be mentioned in the between block (here, by its variance): a variable that appears in both blocks is a shared variable (Section 16.4.2), and a variable that only appears in the within block would have no random intercept at all. The between component of Reaction is the random intercept, its between-level intercept is the fixed intercept of the mixed model, and its between-level variance is the intercept variance. The within-level variance of Reaction is the residual variance.

When the two outputs are compared, the fixed effects can be read off directly, but the variance components cannot. The output of lmer() shown above reports the random effects and the residual as standard deviations (the Std.Dev. column), and the association between the random intercept and the random slope as a correlation (the Corr column). lavaan reports variances and a covariance. The VarCorr() function of lme4 gives the variance components in both metrics:

vc <- as.data.frame(lme4::VarCorr(fit_lmer))
vc
       grp        var1 var2      vcov       sdcor
1  Subject (Intercept) <NA> 565.51521 23.78056372
2  Subject        Days <NA>  32.68219  5.71683353
3  Subject (Intercept) Days  11.05537  0.08131969
4 Residual        <NA> <NA> 654.94107 25.59181650

The vcov column contains the two variances, the covariance and the residual variance (the metric of lavaan), and the sdcor column contains the standard deviations and the correlation (the metric of the printed lmer() output). The values of the vcov column, preceded by the two fixed effects, can be put next to the lavaan estimates:

c(lme4 = logLik(fit_lmer), lavaan = logLik(fit_ss))
     lme4    lavaan 
-875.9697 -875.9697 
est <- coef(fit_ss)
idx <- c("Reaction~1.l2", "slope~1.l2", "Reaction~~Reaction.l2",
         "slope~~slope.l2", "slope~~Reaction.l2", "Reaction~~Reaction")
round(cbind(lavaan = est[idx],
            lme4 = c(lme4::fixef(fit_lmer), vc$vcov)), 3)
                       lavaan    lme4
Reaction~1.l2         251.405 251.405
slope~1.l2             10.467  10.467
Reaction~~Reaction.l2 565.514 565.515
slope~~slope.l2        32.682  32.682
slope~~Reaction.l2     11.056  11.055
Reaction~~Reaction    654.941 654.941

The two fits are the same: the log-likelihoods agree, and so do the estimates. The differences in the third decimal of two variance components are due to the stopping rules of the two optimizers; they have no visible effect on the log-likelihood.

The cluster-specific coefficients are obtained with lavPredict(), as the predicted values of the between-level latent variables. Note that lavaan returns the coefficients themselves (fixed effect plus deviation), which is what coef() returns for a mixed model, while ranef() returns the deviations only:

head(lavPredict(fit_ss, level = 2L)[, c("Reaction", "slope")], 3)
     Reaction     slope
[1,] 254.2208 19.542817
[2,] 211.3567  1.823207
[3,] 212.9720  4.953896
head(coef(fit_lmer)$Subject, 3)
    (Intercept)      Days
308    254.2208 19.542820
309    211.3566  1.823219
310    212.9720  4.953907

16.13.2 Random slopes are correlated by default

In the sleepstudy model, the covariance between the random slope and the random intercept was not written in the model syntax, but it is a free parameter of the model. The sem(), cfa() and growth() functions set the option auto_cov_rv = TRUE, which allows a random slope to covary with every other random effect of the between level:

  • the other random slopes;

  • the random intercepts, which are the between components of the observed variables that are also modeled at the within level (the exogenous covariates are not included);

  • the between-level factors: if a shared variable is an indicator of a between-level factor, the factor takes the place of the random intercept, and the random slope covaries with the factor and not with the residual of the indicator.

No covariance is added if one of the two variables is regressed, directly or indirectly, on the other, or if the variance of one of them is fixed to zero. If one of them (or both) is a dependent variable at the between level, the covariance is a residual covariance. As always, a covariance that is written in the model syntax takes precedence, so that a single covariance is removed by fixing it to zero (slope ~~ 0*Reaction). All of them are removed at once with auto_cov_rv = FALSE, or with orthogonal = TRUE. The lavaan() function, which adds nothing automatically, uses auto_cov_rv = FALSE; the covariances must then be written out, like the variances. With mimic = "Mplus", the covariances are not added either, since in Mplus the random effects are uncorrelated unless a covariance is requested. Note that earlier versions of lavaan (before 0.7-3) did not add these covariances: random slopes were uncorrelated with the other random effects unless the covariances were written in the model syntax, and results obtained with those versions may therefore differ.

The main reason for this default is location invariance. Adding a constant to a covariate (centering it, for example, or counting the days from 1 instead of 0) should not change the model. With a random slope, the random intercept is the expected outcome of a cluster where the covariate equals zero, and moving the zero point redefines it: if x^{*} = x - c, then

b_{0j} + s_j\, x_{ji} = (b_{0j} + c\, s_j) + s_j\, x^{*}_{ji},

so that the new random intercept is b_{0j}^{*} = b_{0j} + c\, s_j. Its variance and its covariance with the slope follow:

\text{Var}(b_{0j}^{*}) = \text{Var}(b_{0j}) + 2c\, \text{Cov}(b_{0j}, s_j) + c^2\, \text{Var}(s_j), \qquad \text{Cov}(b_{0j}^{*}, s_j) = \text{Cov}(b_{0j}, s_j) + c\, \text{Var}(s_j). \tag{16.15}

If the covariance is a free parameter, the shifted model is a reparameterization of the original one: the two fits have the same log-likelihood, the same slope variance and the same residual variance, and the remaining parameters are related by Equation 16.15. If the covariance is fixed to zero, this is no longer true. A covariance that is zero for one choice of origin is nonzero (by c\, \text{Var}(s_j)) for every other, so that each origin defines a different model, with a different fit and a different slope variance. A default should not depend on an arbitrary origin. To illustrate, we center Days at the middle of the study, and fit the model with and without the covariance:

ss_c <- sleepstudy
ss_c$Days <- ss_c$Days - 4.5
fit_ss_c  <- sem(model_ss, data = ss_c, cluster = "Subject")
fit_ss_0  <- sem(model_ss, data = sleepstudy, cluster = "Subject",
                 auto_cov_rv = FALSE)
fit_ss_c0 <- sem(model_ss, data = ss_c, cluster = "Subject",
                 auto_cov_rv = FALSE)
logl <- c(logLik(fit_ss), logLik(fit_ss_c),
          logLik(fit_ss_0), logLik(fit_ss_c0))
matrix(logl, 2, 2, dimnames = list(c("Days", "Days - 4.5"),
                                   c("correlated", "uncorrelated")))
           correlated uncorrelated
Days        -875.9697    -876.0016
Days - 4.5  -875.9697    -881.2217

With the covariance, the two log-likelihoods are identical; without it, they differ. The estimates show the same pattern:

idx <- c("Reaction~~Reaction", "Reaction~~Reaction.l2",
         "slope~~slope.l2", "Reaction~1.l2", "slope~1.l2")
round(rbind("correlated, Days" = coef(fit_ss)[idx],
            "correlated, Days - 4.5" = coef(fit_ss_c)[idx],
            "uncorrelated, Days" = coef(fit_ss_0)[idx],
            "uncorrelated, Days - 4.5" = coef(fit_ss_c0)[idx]), 3)
                         Reaction~~Reaction Reaction~~Reaction.l2
correlated, Days                    654.941               565.514
correlated, Days - 4.5              654.941              1326.830
uncorrelated, Days                  653.116               584.250
uncorrelated, Days - 4.5            654.941              1326.827
                         slope~~slope.l2 Reaction~1.l2 slope~1.l2
correlated, Days                  32.682       251.405     10.467
correlated, Days - 4.5            32.682       298.508     10.467
uncorrelated, Days                33.633       251.405     10.467
uncorrelated, Days - 4.5          32.682       298.508     10.467

In the correlated model, centering changes the intercept, its variance and its covariance with the slope (not shown), as it should: they now describe the middle of the study instead of day zero. Nothing else changes. In the uncorrelated model, the residual variance and the slope variance change as well.

A second reason is consistency: at the between level, the random slopes are exogenous latent variables (unless they are regressed on other variables), and exogenous latent variables are correlated by default in the sem() and cfa() functions. The price is a larger number of parameters: with several random slopes, the covariance matrix of the random effects grows quickly, and a model with many random effects and few clusters may be hard to estimate. The covariances can then be removed selectively, or all at once, but preferably after choosing a meaningful zero point for the covariates, because that choice is then part of the model.

16.13.3 Why the likelihood is conditional on the covariates

The product of a random slope and a covariate has far-reaching consequences. Write s_j for the slope of cluster j, so that y_{ji} = \ldots + s_j\, x_{ji} + \ldots Even if s_j and x_{ji} are both normal, their product is not, and the joint distribution of (y, x) is no longer multivariate normal. Given the covariate, however, the outcome is still normal, with a covariance between two units of the same cluster that depends on their covariate values:

\text{Cov}(y_{ji}, y_{ji'} \mid x_{ji}, x_{ji'}) = \ldots + x_{ji}\, x_{ji'}\, \text{Var}(s_j).

Two consequences follow. First, the model is defined for the outcomes given the covariates: the covariates that carry a random slope are treated as fixed, and the likelihood that is maximized is the likelihood of \mathbf{y} given \mathbf{x}. This is what every mixed-model program does, and it is the reason why fixed_x = TRUE is required for these models. In lavaan, the likelihood is conditional on all the exogenous covariates: those that carry a random slope, any other within-only exogenous covariate, and the between-only exogenous covariates. Second, the two matrices \boldsymbol{\Sigma}_W and \boldsymbol{\Sigma}_B no longer summarize the model: every cluster (in fact, every pair of units) has its own covariance structure. The sufficient statistics of Section 16.5.2 lose their role, and so does the unrestricted model of Section 16.6: there is no saturated model in terms of a within and a between covariance matrix that the fitted model is a restriction of. As a result, there is no chi-square test statistic, and no fit measure that is derived from it. What remains are the log-likelihood and the information criteria, exactly as in a mixed model.

One aspect is more favorable than it may seem. Conditional on the covariates, the random slopes enter the model linearly, just like the random intercepts, and all the cluster-level random variables can be integrated out analytically. No numerical integration is needed, as long as the covariates that carry the random slopes are observed. Random slopes for latent covariates are a different matter; see Section 16.13.7.

16.13.4 Random slopes in the parameter table and the model matrices

A random slope is not a new kind of parameter, and no new model matrix is needed to hold it. The parameter table of the sleepstudy model shows how it is represented:

pt <- parTable(fit_ss)
pt[, c("lhs", "op", "rhs", "level", "free", "rv", "exo")]
        lhs op      rhs level free    rv exo
1  Reaction  ~     Days     1    0 slope   0
2  Reaction ~~ Reaction     1    1         0
3      Days ~~     Days     1    0         1
4  Reaction ~1              1    0         0
5      Days ~1              1    0         1
6  Reaction ~~ Reaction     2    2         0
7     slope =~    slope     2    0 slope   0
8     slope ~~    slope     2    3         0
9     slope ~~ Reaction     2    4         0
10 Reaction ~1              2    5         0
11    slope ~1              2    6         0

Three changes are visible. In the within block, the regression of Reaction on Days is still present, but it is fixed to zero, and the rv column contains the name of the random slope: the coefficient has moved to the between level. In the between block, a row slope =~ slope (also fixed) does nothing more than declare slope as a latent variable without indicators; its intercept and variance follow, as for any other latent variable. And the covariate Days is flagged as exogenous (exo is 1), with its mean and variance fixed to their sample values; these values play no role in the likelihood, which conditions on the covariate. The model matrices reflect this:

lavInspect(fit_ss, "est")$Subject[c("lambda", "psi", "alpha")]
$lambda
         slope Reactn
Reaction     0      1

$psi
           slope  Reactn
slope     32.682        
Reaction  11.056 565.514

$alpha
          intrcp
slope     10.467
Reaction 251.405

In the between block, the random slope is an ordinary element of the latent vector \boldsymbol{\eta}_B: it has a column of zeros in \boldsymbol{\Lambda}_B (it has no indicators), and its mean, its variance, and its covariance with the random intercept are found in \boldsymbol{\alpha}_B and \boldsymbol{\Psi}_B. (The observed variable Reaction also appears in the latent vector, because lavaan upgrades the observed variables that are involved in the structural part of a model to single-indicator latent variables; see Section 4.3.4.) If the slope is regressed on other between-level variables, or predicts them, the coefficients are found in \mathbf{B}_B. All the usual tools of the between model are therefore available for the random slopes. The within block has nothing special either, apart from the zero in \mathbf{B}_W where the slope used to be. What is special is the way the two blocks are combined into a likelihood.

16.13.5 The model for a cluster

Four kinds of observed variables must be distinguished. The P \times 1 vector \mathbf{y}_{ji} contains the level-1 outcomes of unit i in cluster j: the shared variables and the within-only endogenous variables. The vector \mathbf{x}_{ji} contains the within-only exogenous covariates, with or without a random slope. At the cluster level, \mathbf{w}_j contains the between-only exogenous covariates, and \mathbf{z}_j the between-only endogenous variables (the indicators of a between-level factor, say). The likelihood is that of the \mathbf{y}_{ji} and \mathbf{z}_j, given the \mathbf{x}_{ji} and \mathbf{w}_j. To keep the notation light, we assume in what follows that there are no between-only endogenous variables; they add one more block to the expressions below (appendix E.7.3).

All the randomness at the cluster level is collected in a single vector \mathbf{u}_j of length K. It contains the between-level latent variables (the between factors, the random slopes, and the random intercepts of the outcomes that have been upgraded to latent variables), followed by the between-level residuals of the shared variables, as far as their variance is not fixed to zero. Given the cluster-level covariates, \mathbf{u}_j is normal, with a mean that is linear in \mathbf{w}_j and a covariance matrix that is the same for all clusters:

\mathbf{u}_j \mid \mathbf{w}_j \sim \mathcal{N}\bigl(\boldsymbol{\mu}_{u,j},\, \boldsymbol{\Sigma}_u\bigr), \qquad \boldsymbol{\mu}_{u,j} = \boldsymbol{\mu}_u + \mathbf{C}\,(\mathbf{w}_j - \boldsymbol{\mu}_w). \tag{16.16}

These moments are those of the between model. The mean vector and the covariance matrix of \boldsymbol{\eta}_B are (\mathbf{I} - \mathbf{B}_B)^{-1}\boldsymbol{\alpha}_B and (\mathbf{I} - \mathbf{B}_B)^{-1}\boldsymbol{\Psi}_B (\mathbf{I} - \mathbf{B}_B^{\prime})^{-1}; conditioning on the elements of \boldsymbol{\eta}_B that correspond to the covariates \mathbf{w}_j gives the latent part of \boldsymbol{\mu}_u, \mathbf{C} and \boldsymbol{\Sigma}_u, and the residual part is added as a diagonal block taken from \boldsymbol{\Theta}_B. In mixed-model terms, \boldsymbol{\Sigma}_u is the covariance matrix of the random effects, but the random effects are not centered: their means \boldsymbol{\mu}_{u,j} carry the fixed effects (the mean slopes, the between-level intercepts, and the effects of the cluster-level covariates).

Given \mathbf{u}_j and the covariates, the units of a cluster are independent, with

\mathbf{y}_{ji} \mid \mathbf{u}_j, \mathbf{x}_{ji} \sim \mathcal{N}\bigl(\boldsymbol{\mu}_y + \boldsymbol{\Pi}\,\mathbf{x}_{ji} + \mathbf{Q}_{ji}\,\mathbf{u}_j,\; \boldsymbol{\Sigma}_W\bigr). \tag{16.17}

All four ingredients are computed from the within model matrices. \boldsymbol{\Sigma}_W is the model-implied covariance matrix of the within block (Equation 16.3), restricted to the outcomes, with the variances and covariances of the conditioned covariates set to zero in \boldsymbol{\Psi}_W. Because the cells of the random slopes are zero in \mathbf{B}_W, this is the covariance matrix of the outcomes given the random effects and the covariates. The vector \boldsymbol{\mu}_y contains the within-level intercepts, and \boldsymbol{\Pi} the reduced-form coefficients of the outcomes on the covariates that stem from fixed regressions: the corresponding columns of the total-effect matrix \boldsymbol{\Lambda}_W(\mathbf{I} - \mathbf{B}_W)^{-1}. Finally, the P \times K matrix \mathbf{Q}_{ji} translates the cluster-level variables into the outcomes of unit i:

\mathbf{Q}_{ji} = \mathbf{Q}_0 + \sum_{r=1}^{R} x_{ji}^{(r)}\, \boldsymbol{\lambda}_r\, \mathbf{e}_{k(r)}^{\prime}. \tag{16.18}

The constant part \mathbf{Q}_0 is what the random-intercept model already has: the between-level loadings \boldsymbol{\Lambda}_B in the columns of the between latent variables (rows of the shared variables), and unit vectors in the columns of the between residuals. The columns of the random slopes are zero in \mathbf{Q}_0. They are filled by the sum, which has one term for each of the R regressions that carry an rv() modifier. For regression r, x_{ji}^{(r)} is the value of its covariate, \mathbf{e}_{k(r)} is the unit vector that selects its random slope in \mathbf{u}_j, and \boldsymbol{\lambda}_r is the column of \boldsymbol{\Lambda}_W(\mathbf{I} - \mathbf{B}_W)^{-1} that belongs to its dependent variable: the effect on all the outcomes of a unit change in that variable. If the dependent variable is an observed outcome, \boldsymbol{\lambda}_r selects that outcome, and every outcome that depends on it. If the dependent variable is a within-level factor, as in fw ~ rv("s1")*x1, \boldsymbol{\lambda}_r contains the loadings of the factor, and the random slope reaches all its indicators.

For the sleepstudy model, with \mathbf{u}_j containing the slope and the random intercept, we have \boldsymbol{\Sigma}_W = \sigma^2, \boldsymbol{\Pi} = \mathbf{0}, \mathbf{Q}_0 = (0, 1), \boldsymbol{\lambda}_1 = 1, and therefore \mathbf{Q}_{ji} = (x_{ji}, 1): the familiar row of the random-effects design matrix. In general, \mathbf{Q}_{ji} is the SEM counterpart of that row. It differs in two respects: it is not given by the data alone but depends on the model parameters (loadings and regression coefficients), and it has P rows, one for each outcome.

16.13.6 The marginal log-likelihood

Stack the outcomes of cluster j in the vector \mathbf{y}_j of length n_j\, P, and the matrices \mathbf{Q}_{ji} in the n_j\, P \times K matrix \mathbf{Q}_j. Integrating Equation 16.17 over Equation 16.16 gives a normal distribution for \mathbf{y}_j, given the covariates, with covariance matrix

\mathbf{V}_j = \mathbf{I}_{n_j} \otimes \boldsymbol{\Sigma}_W + \mathbf{Q}_j\, \boldsymbol{\Sigma}_u\, \mathbf{Q}_j^{\prime}. \tag{16.19}

This is the covariance matrix \mathbf{Z}\mathbf{G}\mathbf{Z}^{\prime} + \mathbf{R} of the linear mixed model, with \mathbf{Q}_j as the random-effects design matrix. It also contains the random-intercept model as a special case: without random slopes, \mathbf{Q}_{ji} = \mathbf{Q}_0 for every unit, the second term reduces to \boldsymbol{1}_{n_j}\boldsymbol{1}_{n_j}^{\prime} \otimes \mathbf{Q}_0 \boldsymbol{\Sigma}_u \mathbf{Q}_0^{\prime}, and \mathbf{Q}_0 \boldsymbol{\Sigma}_u \mathbf{Q}_0^{\prime} is the between covariance matrix \boldsymbol{\Sigma}_B of Equation 16.5. With random slopes, \mathbf{V}_j differs from cluster to cluster, not only through the cluster size but through the values of the covariates.

As before, \mathbf{V}_j is never formed or inverted. It is the sum of a block-diagonal matrix and a matrix of rank K (at most), and the Woodbury identity and the matrix determinant lemma (appendix B) reduce everything to matrices of order K. Write \mathbf{r}_{ji} = \mathbf{y}_{ji} - \boldsymbol{\mu}_y - \boldsymbol{\Pi}\, \mathbf{x}_{ji} - \mathbf{Q}_{ji}\,\boldsymbol{\mu}_{u,j} for the residual of unit i with respect to its marginal mean, and define three quantities per cluster:

\mathbf{H}_j = \sum_{i=1}^{n_j} \mathbf{Q}_{ji}^{\prime}\boldsymbol{\Sigma}_W^{-1}\mathbf{Q}_{ji}, \qquad \mathbf{g}_j = \sum_{i=1}^{n_j} \mathbf{Q}_{ji}^{\prime}\boldsymbol{\Sigma}_W^{-1}\mathbf{r}_{ji}, \qquad c_j = \sum_{i=1}^{n_j} \mathbf{r}_{ji}^{\prime}\boldsymbol{\Sigma}_W^{-1}\mathbf{r}_{ji}. \tag{16.20}

The log-likelihood contribution of cluster j is then

\begin{aligned} \log L_j = -\frac{1}{2} \Bigl\{\; & n_j\, P \log(2\pi) + n_j \log|\boldsymbol{\Sigma}_W| + \log|\mathbf{I} + \mathbf{H}_j\boldsymbol{\Sigma}_u| \\ & + c_j - \mathbf{g}_j^{\prime}\,\boldsymbol{\Sigma}_u\, (\mathbf{I} + \mathbf{H}_j\boldsymbol{\Sigma}_u)^{-1}\,\mathbf{g}_j \;\Bigr\}. \end{aligned} \tag{16.21}

The interpretation of the three quantities is as follows. \mathbf{H}_j is the information that the data of the cluster carry about its own random effects, and \mathbf{g}_j is the corresponding score. The term c_j is the sum of squared residuals that would be obtained if the random effects were equal to their means, and the last term of Equation 16.21 is the part of it that the random effects explain. The same quantities give the posterior distribution of the random effects, given the data of the cluster:

\mathbf{u}_j \mid \mathbf{y}_j \sim \mathcal{N}\bigl(\boldsymbol{\mu}_{u \mid j},\, \boldsymbol{\Sigma}_{u \mid j}\bigr), \qquad \boldsymbol{\Sigma}_{u \mid j} = \boldsymbol{\Sigma}_u\, (\mathbf{I} + \mathbf{H}_j\boldsymbol{\Sigma}_u)^{-1}, \qquad \boldsymbol{\mu}_{u \mid j} = \boldsymbol{\mu}_{u,j} + \boldsymbol{\Sigma}_{u \mid j}\,\mathbf{g}_j. \tag{16.22}

The posterior means are the empirical Bayes predictions of the random effects (the conditional modes of the mixed model) that lavPredict() returned above, and they are the central ingredient of the EM algorithm and of the analytic gradient. Note that the inverse of \boldsymbol{\Sigma}_u appears nowhere. The usual way of writing these expressions, with (\boldsymbol{\Sigma}_u^{-1} + \mathbf{H}_j)^{-1} as the posterior covariance matrix, breaks down when \boldsymbol{\Sigma}_u is singular, which happens as soon as a variance at the between level is zero. In the form given here, the log-likelihood remains well defined and smooth on the boundary of the parameter space (and even slightly beyond it), as long as every \mathbf{V}_j is positive definite.

A numerical check illustrates these expressions. For the sleepstudy model, we extract \sigma^2, \boldsymbol{\mu}_u and \boldsymbol{\Sigma}_u from the model matrices, and compute the log-likelihood twice: by brute force, from the n_j \times n_j matrix \mathbf{V}_j of Equation 16.19, and from the 2 \times 2 matrices of Equation 16.21:

est      <- lavInspect(fit_ss, "est")
sigma2_w <- est$within$psi["Reaction", "Reaction"]
Sigma_u  <- unclass(est$Subject$psi)       # slope, random intercept
mu_u     <- est$Subject$alpha[, 1]
logl_brute <- logl_reduced <- 0
for (d in split(sleepstudy, sleepstudy$Subject)) {
  n_j <- nrow(d)
  Q_j <- cbind(d$Days, 1)
  r_j <- d$Reaction - drop(Q_j %*% mu_u)
  # brute force: the n_j x n_j matrix V_j
  V_j <- sigma2_w * diag(n_j) + Q_j %*% Sigma_u %*% t(Q_j)
  logl_brute <- logl_brute - 0.5 * (n_j * log(2 * pi) + log(det(V_j)) +
    drop(t(r_j) %*% solve(V_j, r_j)))
  # reduced form: 2 x 2 matrices only
  H_j <- crossprod(Q_j) / sigma2_w
  g_j <- crossprod(Q_j, r_j) / sigma2_w
  c_j <- sum(r_j^2) / sigma2_w
  IHS <- diag(2) + H_j %*% Sigma_u
  logl_reduced <- logl_reduced - 0.5 * (n_j * log(2 * pi) +
    n_j * log(sigma2_w) + log(det(IHS)) + c_j -
    drop(t(g_j) %*% Sigma_u %*% solve(IHS, g_j)))
}
c(brute = logl_brute, reduced = logl_reduced, lavaan = logLik(fit_ss))
    brute   reduced    lavaan 
-875.9697 -875.9697 -875.9697 

One more property makes the approach practical. With random slopes, the classical sufficient statistics no longer exist, since the likelihood depends on the individual values of the covariates. But \mathbf{Q}_{ji} and \mathbf{r}_{ji} are linear in (\mathbf{y}_{ji}, \mathbf{x}_{ji}), so that the sums in Equation 16.20 are functions of the cross-products of the outcomes and the covariates within each cluster (\sum_i \mathbf{x}_{ji}, \sum_i \mathbf{x}_{ji}\mathbf{x}_{ji}^{\prime}, \sum_i \mathbf{x}_{ji}\mathbf{y}_{ji}^{\prime}, and so on). These cross-products are computed once, in a single pass over the data. After that, an evaluation of the log-likelihood (or of its gradient) is a loop over the clusters with matrices of order P and K, and its cost no longer depends on the cluster sizes. The expressions are given in appendix E.7.2.

16.13.7 Random slopes for latent covariates

The covariate that carries a random slope may also be a latent variable of the within level:

level: 1
  fxw =~ x1 + x2 + x3
  fyw =~ y1 + y2 + y3
  fyw ~ rv("s")*fxw
level: 2
  fxb =~ x1 + x2 + x3
  fyb =~ y1 + y2 + y3
  fyb ~ fxb

(The covariances of the random slope s with fxb and with the residual of fyb are added by default; see Section 16.13.2.) Now the product s_j\, \eta_{x,ji} involves two unobserved variables. There is nothing to condition on, the product of two normal variables is not normal, and the marginal likelihood has no closed form. Numerical integration is unavoidable, but it can be confined to a small part of the model (Rockwood, 2020). Divide the cluster-level variables \mathbf{u}_j into the random slopes that multiply a latent covariate (the nonlinear part) and all the rest (the linear part: random intercepts, between factors, random slopes for observed covariates). Given the values of the nonlinear slopes, the slopes are ordinary regression coefficients that can be written into \mathbf{B}_W, and the model is again of the form of Equation 16.17, with a closed-form likelihood. The marginal likelihood of a cluster is therefore a low-dimensional integral of closed-form likelihoods,

L_j = \int L_j(\mathbf{b})\, \phi(\mathbf{b};\, \boldsymbol{\mu}_s, \boldsymbol{\Sigma}_s)\, d\mathbf{b} \;\approx\; \sum_{d=1}^{D} \omega_d\, L_j(\mathbf{b}_d), \tag{16.23}

where \mathbf{b} runs over the values of the nonlinear slopes, \phi(\cdot) is their normal density, and L_j(\mathbf{b}) is Equation 16.21 evaluated for the linear part, conditional on \mathbf{b}. The integral is approximated by Gauss–Hermite quadrature with D nodes \mathbf{b}_d and weights \omega_d. The dimension of the integral is the number of random slopes with a latent covariate (often just one), whatever the number of other random effects in the model. The number of nodes per dimension is set by the integration_ngh option (current default 21). The per-cluster cross-products are reused at every node, so that the cost is roughly that of the closed-form likelihood times the number of nodes.

The same route is taken when the covariate is an observed variable that appears in both level blocks:

level: 1
  y ~ rv("s")*x
level: 2
  y ~ x

A shared variable is decomposed into a latent within and a latent between component (Section 16.3.1), and the random slope multiplies the latent within component of x. This is the two-level counterpart of centering a covariate within clusters, with latent instead of observed cluster means, and the between-level regression y ~ x then gives the between effect. This is the latent-covariate contextual model of Lüdtke et al. (2008). Note the contrast with a within-only covariate, which is not decomposed: there, the slope multiplies the observed values, the covariate is conditioned upon, and no integration is needed. The role of the covariate (within-only or shared) thus decides which model is fitted, and how.

16.13.8 Estimation and inference

The objective function is the same as for the random-intercept model (Equation 16.11), with the per-cluster log-likelihoods of Equation 16.21 (or the logarithm of Equation 16.23) in the place of Equation 16.8. The gradient is analytic. The model parameters enter the likelihood only through the small set of ingredients of Section 16.13.5 (\boldsymbol{\Sigma}_W, \boldsymbol{\mu}_y, \boldsymbol{\Pi}, the \boldsymbol{\lambda}_r, \mathbf{Q}_0, \boldsymbol{\mu}_u, \mathbf{C} and \boldsymbol{\Sigma}_u), and the derivatives with respect to these ingredients are functions of the posterior moments of Equation 16.22 and the per-cluster cross-products (appendix E.7.5). A gradient therefore costs about as much as one evaluation of the log-likelihood. The unrestricted two-level model of Section 16.6 is still estimated, although it is not a saturated model for these data: its within and between moments provide the starting values, as in Section 16.7.1.

With complete data, the default optimizer is the quasi-Newton method of chapter 7 (see Section 7.1). The alternative is an EM algorithm (Dempster et al., 1977; Laird & Ware, 1982), requested with optim_method = "em". It treats the cluster-level variables \mathbf{u}_j as missing data. In the E-step, their posterior moments of Equation 16.22 are turned into expected first and second moments of the complete data; the M-step is, as in Section 16.7.2, a two-group single-level model that is fitted to these moments, in which the random slopes have become observed variables of the between group (appendix E.7.6). The EM algorithm is not available for all models with random slopes (not for latent covariates, for instance, nor when a covariate with a random slope also has a fixed effect on another variable); lavaan then switches to the quasi-Newton optimizer, with a warning if EM was requested. With missing data (missing = "ml"), the EM algorithm is the default, as for all two-level models. The pattern of missing values only changes the weight matrix \boldsymbol{\Sigma}_W^{-1} in Equation 16.20, which becomes the inverse of the observed part of \boldsymbol{\Sigma}_W for each unit; the integration over \mathbf{u}_j is not affected (appendix E.7.4).

The variance of a random slope is often small, and with several random slopes the covariance matrix of the random effects easily drifts outside the admissible region during the iterations. For models with random slopes, the current default is therefore pd_lv = "auto" (unless mimic = "Mplus"): the covariance matrix of the latent variables (random slopes included) is kept positive definite wherever this is possible (Section 7.11.4). When the solution is in the interior, this has no effect on the results; when it ends on the boundary (a slope variance of zero, or a perfect correlation between two random effects), a warning says so.

The standard errors are based on the observed information, obtained by numerically differentiating the analytic gradient. Robust standard errors (se = "robust.huber.white", or estimator = "MLR") use the sandwich estimator of Equation 8.28, in which the clusters are the independent units. Both of its ingredients are computed in the space of the model parameters directly:

\widehat{\text{Cov}}(\hat{\boldsymbol{\vartheta}}) = \mathbf{H}^{-1}\, \mathbf{J}\, \mathbf{H}^{-1}, \qquad \mathbf{J} = \sum_{j=1}^{N_J} \mathbf{s}_j\, \mathbf{s}_j^{\prime}, \tag{16.24}

where \mathbf{H} is the observed information matrix (of the total log-likelihood) and \mathbf{s}_j is the derivative of \log L_j with respect to the model parameters; these cluster scores are a by-product of the analytic gradient.

Without a chi-square statistic, models are compared by their log-likelihoods. The function fitMeasures() returns the log-likelihood and the information criteria only, and lavTestLRT() computes the likelihood ratio test for nested models from the log-likelihoods (Section 11.2.2). Both models must condition on the same covariates, otherwise their log-likelihoods are not comparable. As an example, we test whether the two random effects of the sleepstudy model are uncorrelated (given that the days are counted from zero; see Section 16.13.2):

model_ss0 <- '
  level: 1
    Reaction ~ rv("slope")*Days
  level: 2
    slope ~~ 0*Reaction
'
fit_ss0 <- sem(model_ss0, data = sleepstudy, cluster = "Subject")
lavTestLRT(fit_ss0, fit_ss)
Likelihood Ratio Test (casewise loglikelihoods)

        Npar    AIC    BIC  logLik Chisq diff Df diff Pr(>Chisq)
fit_ss     6 1763.9 1783.1 -875.97                              
fit_ss0    5 1762.0 1778.0 -876.00   0.063911       1     0.8004

This test concerns a covariance. A test of a slope variance against zero is, as in any mixed model, a test on the boundary of the parameter space, for which the chi-square reference distribution is conservative. With robust standard errors, fitMeasures() also returns the scaling correction factor of the fitted model,

c = \frac{\mathrm{tr}\bigl(\mathbf{H}^{-1}\mathbf{J}\bigr)}{T}, \tag{16.25}

where T is the number of free parameters. It equals one (asymptotically) if the model is correctly specified and the data are normal, and it is the quantity that a scaled difference test in the log-likelihood metric needs (Satorra & Bentler, 2001): for two nested models with T_0 < T_1 parameters and scaling factors c_0 and c_1, twice the difference of the log-likelihoods is divided by (T_1 c_1 - T_0 c_0)/(T_1 - T_0).

fit_ss_mlr <- sem(model_ss, data = sleepstudy, cluster = "Subject",
                  estimator = "MLR")
fitMeasures(fit_ss_mlr, c("logl", "scaling_factor_h0"))
             logl scaling.factor.h0 
         -875.970             1.934 

Finally, lavPredict() returns the posterior means of Equation 16.22 for the between-level latent variables, the random slopes included (level = 2L); adding se = "standard" gives their posterior standard deviations as an attribute. For models with a random slope for a latent covariate, the posterior is a mixture over the quadrature nodes, and the predictions are the means of that mixture. With level = 1L, the within-level factor scores are computed given the posterior means of the cluster-level variables; since the scores are linear in these variables, the result is again a posterior mean (see Section 13.3.10 and appendix E.7.8).

16.13.9 A structural equation model with a random slope

What distinguishes the SEM version from the mixed model is that the dependent variable (and, as we have seen, the covariate) of a random slope may be latent. In the running example of this chapter, the regression of the within factor on x1 is made random as follows:

model_rs <- '
  level: 1
    fw =~ y1 + y2 + y3
    fw ~ rv("s1")*x1 + x2 + x3
  level: 2
    fb =~ y1 + y2 + y3
    fb ~ w1 + w2
    s1 ~ 1        # the mean slope
    s1 ~~ s1      # the slope variance
'
fit_rs <- sem(model_rs, data = Demo.twolevel, cluster = "cluster")
subset(parameterEstimates(fit_rs, ci = FALSE), lhs == "s1")
   lhs op rhs block level   est    se      z pvalue
29  s1 ~1         2     2 0.509 0.023 21.738  0.000
30  s1 ~~  s1     2     2 0.003 0.008  0.326  0.745
39  s1 ~~  fb     2     2 0.041 0.022  1.899  0.058

Here, the random slope s1 reaches the three indicators through the loadings of fw (the vector \boldsymbol{\lambda}_1 of Equation 16.18 contains these loadings), and the vector \mathbf{u}_j consists of fb, s1, and the three between-level residuals. The intercept and the variance of the slope were written out for clarity only; they are added by default. So is the (residual) covariance between s1 and fb: the three indicators are shared variables, but the between-level factor takes the place of their random intercepts (Section 16.13.2). The mean slope is close to the fixed coefficient of the random-intercept model, and the slope variance is very small compared to its standard error: the Demo.twolevel data were generated without random slopes, and the estimates are in line with this. At the between level, s1 could also be regressed on w1 and w2.

The treatment of random slopes comes with a number of limitations in version 0.7-4. As explained in Section 16.13.3, there is no chi-square test statistic and there are no fit indices. In addition:

  • random slopes require raw, continuous data, a single group, estimator = "ML" (or "MLR") and fixed_x = TRUE; the least-squares estimators of Section 16.11.1 and the sampling weights of Section 16.10 are not available;

  • the automatic bounds (the bounds= argument) are not available: a warning is given, and the model is fitted without them;

  • between-only endogenous variables must be indicators of a between-level factor (they cannot take part in regressions), with a residual variance that is not fixed to zero;

  • the same rv() name cannot be attached to both an observed and a latent covariate;

  • lavPredict() provides the posterior means only (no other types of factor scores, and no standard errors at the within level).

Missing values in the outcomes are handled with missing = "ml", for the level-1 outcomes and for the between-only indicators alike (clusters with a missing indicator are retained). The exogenous covariates must be complete, since the likelihood is conditional on them; cases with a missing covariate are removed. A covariate with missing values can still be used by bringing it into the model as the single indicator of a latent variable: at the between level with a small fixed residual variance (zb =~ 1*z and z ~~ 0.001*z), and at the within level, for a covariate that carries a random slope, with a zero residual variance (xw =~ 1*x and x ~~ 0*x), which switches to the latent-covariate route of Section 16.13.7. The section “Random slopes” of ?model.syntax documents the current state.

16.14 Lagged variables in long panel data

Intensive longitudinal data (daily diaries, experience sampling) come in long format: one row per person and occasion, with many occasions per person. A two-level model treats the occasions as the level-1 units, nested in persons, and the natural within-person model is autoregressive: today’s score is regressed on yesterday’s. The panel argument of the fitting functions (Section 2.8.6) names the id and the time variable. With a two-level model (with level: blocks), the data are not reshaped to the wide format: each row remains an occasion, and the id variable is the cluster variable. An index that is not bound in a formula then refers to the time variable: y[t-1] is the value of y at the previous occasion of the same person, y[t-2] the value two occasions earlier, and y[t+1] the next one. A name without an index is the value at the current occasion. lavaan creates the lagged variables in the data, under the names y.lag1, y.lag2 (if lag > 0), and y.lead1, y.lead2 (if lag < 0) and they appear under these names in the output; the lag column of the parameter table holds the lag (1 for y ~ y.lag1).

We simulate a diary study with 100 persons and 30 days, in which two variables follow a bivariate first-order autoregressive process around person-specific means:

set.seed(123)
n_persons <- 100; n_days <- 30
Diary <- do.call(rbind, lapply(seq_len(n_persons), function(j) {
  mu <- rnorm(2)                 # person-specific means
  y <- x <- numeric(n_days)
  y[1] <- mu[1] + rnorm(1); x[1] <- mu[2] + rnorm(1)
  for (t in 2:n_days) {
    y[t] <- mu[1] + 0.4 * (y[t-1] - mu[1]) + 0.2 * (x[t-1] - mu[2]) +
            rnorm(1, sd = 0.8)
    x[t] <- mu[2] + 0.3 * (x[t-1] - mu[2]) + 0.1 * (y[t-1] - mu[1]) +
            rnorm(1, sd = 0.8)
  }
  data.frame(person = j, day = seq_len(n_days), y = y, x = x)
}))
head(Diary, 3)
  person day         y          x
1      1   1 0.9982327 -0.1596691
2      1   2 0.1805395  1.3188978
3      1   3 0.4144785 -0.7034024

The two-level model regresses each variable on the lagged values of both at the within level, with correlated residuals, and lets the person means covary at the between level:

model_var <- '
  level: 1
    y ~ y[t-1] + x[t-1]
    x ~ x[t-1] + y[t-1]
    y ~~ x
  level: 2
    y ~~ y + x
    x ~~ x
'
fit_var <- sem(model_var, data = Diary,
               panel = c(id = "person", time = "day"))
summary(fit_var)
lavaan 0.7-4 ended normally after 30 iterations

  Estimator                                         ML
  Optimization method                           NLMINB
  Number of model parameters                        12

  Number of observations                          2900
  Number of clusters [person]                      100


Parameter Estimates:

  Standard errors                             Standard
  Information                                 Observed
  Observed information based on                Hessian


Level 1 [within]:

Regressions:
                   Estimate  Std.Err  z-value  P(>|z|)
  y ~                                                 
    y.lag1            0.383    0.018   21.038    0.000
    x.lag1            0.184    0.018   10.228    0.000
  x ~                                                 
    x.lag1            0.311    0.019   16.549    0.000
    y.lag1            0.125    0.018    7.103    0.000

Covariances:
                   Estimate  Std.Err  z-value  P(>|z|)
 .y ~~                                                
   .x                -0.017    0.012   -1.431    0.153

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y                 0.633    0.017   37.288    0.000
   .x                 0.644    0.017   37.304    0.000


Level 2 [person]:

Covariances:
                   Estimate  Std.Err  z-value  P(>|z|)
 .y ~~                                                
   .x                -0.169    0.047   -3.595    0.000

Intercepts:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y                 0.072    0.061    1.184    0.237
   .x                 0.003    0.067    0.050    0.960

Variances:
                   Estimate  Std.Err  z-value  P(>|z|)
   .y                 0.351    0.057    6.161    0.000
   .x                 0.423    0.067    6.272    0.000

The estimates are close to the population values (0.4, 0.2, 0.3, and 0.1). The lags follow the values of the time variable, which must contain integers: if an occasion is missing, the lagged value at the next occasion is missing too, so that a gap is never bridged. Occasions without the values of the lagged predictors (the first occasion of each person, and the first occasion after a gap) are not used, which is why the header counts 2900 rather than 3000 observations. A random autoregressive effect is written with the rv() modifier of Section 16.13, as in y ~ rv("phi")*y[t-1], and can be regressed on person-level covariates at the between level.

Two aspects of this model deserve attention. First, the lagged variables are observed variables at the within level: they are not centered, and the likelihood is conditional on them (and on all other observed within-only covariates), exactly as in a mixed model with a lagged predictor (the lme4 package gives identical results for the univariate case) and as in Mplus with lagged variables computed by hand and declared as WITHIN variables. The first occasion of each person is conditioned upon, but the random intercept is assumed to be independent of it, although in an autoregressive process it is not: this is the initial-conditions problem, which matters mostly for short series, and a common remedy is to add the first observed value of each person as a between-level covariate. This treatment differs from the dynamic structural equation models (DSEM) of Mplus, which decompose the lagged variables into latent within and between parts (latent centering) and use Bayesian estimation. Second, since the standard two-level likelihood treats a within-only covariate as having no between-level part, which a lagged outcome clearly has, these models use the conditional likelihood of the random-slope models (Section 16.13.3), also without random slopes. The restrictions of that likelihood apply: estimator "ML" or "MLR", continuous data (missing = "ml" is supported), and no chi-square test statistic, although the log-likelihood and the information criteria are available (Section 10.6), and nested models can be compared with lavTestLRT() (Section 11.2.2).

16.15 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. For reference, Table 16.1 maps the topics of this chapter to the source files that implement them.

Table 16.1: Source files behind the two-level implementation.
Topic File(s)
Cluster structure of the data (Lp) lav_data.R
Two-level sufficient statistics (YLp) lav_samplestats.R
Log-likelihood, gradient, scores, information, EM (complete data) lav_mvnorm_cluster.R
lav_mvnorm_cluster_kernels.R
Same, conditional_x = TRUE lav_mvreg_cluster.R
Same, missing = "ml" lav_mvnorm_cluster_missing.R
Louis observed information (missing data) lav_mvnorm_cluster_missing_louis.R
\mathsf{H}_1 estimation (dispatch) lav_h1_implied.R
lav_lavaan_step06_h1.R
EM acceleration (SQUAREM, quasi-Newton) lav_em_accel.R
Two-level WLS statistics (continuous / categorical) lav_samplestats_wls_2l.R
lav_muthen2007.R
lav_samplestats_wls_2l_cat.R
lav_model_wls_2l_cat.R
Stage-wise univariate/bivariate two-level models lav_uvreg_2l.R
lav_uvord_2l.R
lav_bvreg_2l.R
lav_bvord_2l.R
lav_bvmix_2l.R
Random slopes (rv()) lav_mvnorm_cluster_rs.R
Long panel data (panel=), lagged variables lav_data_panel.R
Level-specific fit measures lav_fit_by_level.R

The quasi-Newton optimizer of Section 16.7.1 is R’s nlminb(), the package-wide default described in the implementation notes of chapter 7 (Section 7.12.1); the hand-off that completes an EM run (Section 16.7.2) calls the same routine, hence the name of the em_args$nlminb_handoff option.

In the internal representation, each level is simply another block: the GLIST slot of the internal model object holds a full set of LISREL matrices for each block, hence two sets per group for a two-level model. A shared variable (one that appears in both level blocks; see Section 16.4.2) is called a both variable in the source code. With fixed_x = TRUE (Section 16.4.6), the rows and columns of the information matrices that correspond to covariate-only moments are zeroed out by means of the x_idx argument that runs through the lav_mvn_cl_* functions.

16.15.1 Two representations of the implied moments

Throughout the complete-data code (the files of Table 16.1), two representations of the model-implied moments are used:

  • the implied representation: one mean vector and covariance matrix per level, exactly as produced by lav_model_implied() and as shown by lavInspect(fit, "implied"): level 1 spans the within-only and shared variables; level 2 spans the shared and between-only variables;

  • the 2l representation: the y/z partition in which the marginal likelihood is naturally expressed, with blocks sigma_w, sigma_b (shared block), sigma_zz, sigma_yz, and the mean parts mu_y (= \mu_W + \mu_B for the shared variables), mu_z.

Two functions map one representation to the other (they are listed in Table 16.3). Both maps are linear scatter/gather operations through a “tilde” variable set that spans all distinct variables across the two levels; because they are linear, the same function that maps parameters forward also serves as the adjoint (transpose) map for gradients.

16.15.2 Function map

The main internal functions are listed below in five tables, one per theme: the sufficient statistics and the \mathsf{H}_1 model (Table 16.2), the complete-data likelihood (Table 16.3), missing data (Table 16.4), least squares and the residual-based tests (Table 16.5), and random slopes (Table 16.6). The source file of a function is named in the text that precedes its table, unless it is given in the table itself.

The first table (Table 16.2) covers the sufficient statistics of Section 16.5.2 and the \mathsf{H}_1 model. The statistics are stored in the @YLp slot: Y2 (the cluster means), Sigma.W (\mathbf{S}_{PW}), mean.d and cov.d (the per-stratum \mathbf{m}_s and \mathbf{C}_s), S.b (the scaled between covariance matrix) and the MUML-derived Sigma.B and S.PW.start that serve as starting values when the \mathsf{H}_1 computation is skipped. The \mathsf{H}_1 model is estimated in step 6 of the fitting sequence, and the result is the @h1 slot.

Table 16.2: Internal functions: sufficient statistics, the \mathsf{H}_1 model and the bounds.
Function Purpose
lav_samp_cl_patterns() sufficient statistics per cluster-size stratum (file lav_samplestats.R)
lav_h1_implied_logl() estimates the \mathsf{H}_1 model by calling one of the two EM functions below (file lav_h1_implied.R)
lav_mvn_cl_em_sat() EM algorithm for the \mathsf{H}_1 model, complete data (file lav_mvnorm_cluster.R)
lav_mvn_cl_mi_em_sat() the same with missing = "ml" (file lav_mvnorm_cluster_missing.R)
lav_pt_add_bounds() the automatic bounds of Section 6.2.2, computed per block (level within group) for two-level models; lav_pt_bounds_ov_var_level() supplies the within and between variances (file lav_partable_bounds.R)

The complete-data likelihood and its derivatives (Table 16.3) are in lav_mvnorm_cluster.R, with the shared kernels in lav_mvnorm_cluster_kernels.R. The gradient and the cluster-wise scores share almost all of their algebra; both are produced by a single engine with a score_mode switch: in gradient mode it loops over the cluster-size strata and aggregates, in score mode it loops over the clusters and returns one row per cluster. A per-cluster-size cache of \boldsymbol{\Sigma}_{(s)}^{-1} factors keeps the score computation fast. The lavScores() function reaches these scores through lav_sc_ml_2l() (file lav_scores.R), which chains them through the model Jacobian.

Table 16.3: Internal functions: the complete-data likelihood and its derivatives.
Function Purpose
lav_mvn_cl_implied22l() maps the implied representation to the 2l representation (Section 16.15.1)
lav_mvn_cl_2l2implied() maps the 2l representation back to the implied representation
lav_mvn_cl_loglik_samp_2l() -2\log L (or \log L) from the sufficient statistics
lav_mvn_cl_dlogl_2l_samp() analytic gradient of -2\log L with respect to (\boldsymbol{\mu}_W, \mathrm{vech}\,\boldsymbol{\Sigma}_W, \boldsymbol{\mu}_B, \mathrm{vech}\,\boldsymbol{\Sigma}_B)
lav_mvn_cl_sc_2l() the same derivatives, but cluster-wise (score rows)
lav_mvn_cl_grad_engine() the engine behind the gradient and the scores (kernels file)
lav_mvn_cl_info_expected() expected information of the \mathsf{H}_1 model
lav_mvn_cl_info_expected_delta() expected information of the \mathsf{H}_0 model
lav_mvn_cl_info_firstorder() first-order information from the cluster scores
lav_model_objective_2l() two-level branch of lav_model_objective(): defines Equation 16.11 and chains the moment-level derivatives through the model Jacobian (file lav_objective.R)
lav_model_delta() the model Jacobian (file lav_model_gradient.R)

For two-level ML models, the model Jacobian follows the mean convention of the \mathsf{H}_1 statistics: the rows of the within means of the shared variables are added to the rows of their between means and then set to zero (fold_means = TRUE), so that the Jacobian matches the layout of the cluster-wise scores and of the \mathsf{H}_1 information matrices. The Louis computation, which works with the complete-data representation, asks for the unfolded version. The same fold is applied to the model-implied means (not to the Jacobian) inside the residual computations of lav_residuals.R, as described in Section 16.4.3; it is skipped with conditional_x = TRUE and for categorical data.

The functions for missing data (missing = "ml"; Table 16.4) are in lav_mvnorm_cluster_missing.R, except for the three Louis functions, which are in lav_mvnorm_cluster_missing_louis.R.

Table 16.4: Internal functions: two-level ML with missing data.
Function Purpose
lav_mvn_cl_mi_loglik_samp_2l() the objective (-2\log L or \log L)
lav_mvn_cl_mi_dlogl_2l_samp() analytic gradient
lav_mvn_cl_mi_sc_2l() cluster-wise scores
lav_mvn_cl_mi_info_firstorder() first-order information from the cluster scores
lav_mvn_cl_mi_h_louis() Louis observed information of the \mathsf{H}_0 model
lav_mvn_cl_mi_info_obs_louis() Louis observed information of the \mathsf{H}_1 model
lav_mvn_cl_mi_scov_louis() the score covariance of the Louis formula
lav_mvn_cl_mi_posterior() the posterior computations of appendix E.6
lav_mvn_cl_mi_estep_ranef() the random effects that lavPredict() and lavInspect(fit, "ranef") return for two-level models with missing data

The EM algorithm for the \mathsf{H}_0 model of Section 16.7.2 is lav_mvn_cl_em_h0() (file lav_mvnorm_cluster.R); the two EM functions for the \mathsf{H}_1 model are in Table 16.2, and the EM functions for random slopes are in Table 16.6. The acceleration schemes (SQUAREM, quasi-Newton) are in lav_em_accel.R.

The least-squares statistics of Section 16.11.1 and Browne’s residual-based tests for two-level models are covered by Table 16.5. Two-level GLS is handled internally as two-level WLS with a different weight matrix: the summary() output shows GLS, but lavInspect(fit, "options")$estimator returns "WLS". The files for the stage-wise univariate and bivariate two-level models of Section 16.11.2 are listed in Table 16.1.

Table 16.5: Internal functions: two-level least squares and the residual-based tests.
Function Purpose
lav_muthen2007() the two-level WLS statistics (file lav_muthen2007.R)
lav_samp_wls_2l() assembles the statistics and the weight matrix per group; for GLS, it takes the normal-theory weight matrix that lav_samp_gamma_2l_g() attaches to its result (file lav_samplestats_wls_2l.R)
lav_samp_gamma_2l_g() the two-level sandwich \hat{\boldsymbol{\Gamma}}, used by the ADF versions of the tests (file lav_samplestats_wls_2l.R)
lav_test_browne_2l() Browne’s residual-based tests for two-level models (file lav_test_browne.R)
lav_model_h1_info() the per-cluster \mathsf{H}_1 information used by these tests (file lav_model_h1_information.R)

The sampling weights of Section 16.10 are processed in lav_data.R: lav_data_cl_weights() checks the cluster weights, and lav_data_cl_unit_weights() rescales the level-1 weights per cluster and computes the (effective) cluster sizes. The rescaled weights are stored with the cluster information of the data, and are picked up from there by the sufficient statistics and by the likelihood functions of the tables above. The default covariances of the random slopes (Section 16.13.2) are added when the parameter table is built, by lav_pt_flat_cov_rv() (file lav_partable_flat.R).

The random-slope computations of Section 16.13 and appendix E.7 (Table 16.6) are all in lav_mvnorm_cluster_rs.R. A model is routed to them as soon as its parameter table contains a nonempty rv column (or, for the lagged variables of Section 16.14, within-only covariates that must be conditioned upon). The results of the first two functions of the table are cached. The quadrature for latent covariates is an outer loop around the closed-form functions.

Table 16.6: Internal functions: random slopes.
Function Purpose
lav_mvn_cl_rs_info() validates the model and builds the index maps: which element of \mathbf{u}_j is which, the cells of the random slopes in the model matrices, the classification of the covariates as observed or latent
lav_mvn_cl_rs_stats() the single pass over the data that produces the per-cluster cross-products
lav_mvn_cl_rs_implied() maps the model matrices to the ingredients of Section 16.13.5
lav_mvn_cl_rs_loglik() evaluates Equation 16.21
lav_mvn_cl_rs_loglik_m() the same with missing data
lav_mvn_cl_rs_cond() quadrature: the conditional ingredients at all nodes
lav_mvn_cl_rs_loglik_nl() quadrature: combines the nodes
lav_mvn_cl_rs_m2ll() dispatches between the closed-form and the quadrature version
lav_mvn_cl_rs_dfphi() gradient: the derivatives with respect to the ingredients
lav_mvn_cl_rs_grad() gradient: the assembly, also per cluster for the scores
lav_mvn_cl_rs_grad_nl() gradient: the quadrature version
lav_mvn_cl_rs_em_ok() decides whether EM is available for a model
lav_mvn_cl_rs_estep() EM: the E-step
lav_mvn_cl_rs_estep_m() EM: the E-step with missing data
lav_mvn_cl_rs_mstep_pt() EM: the two-group parameter table of the M-step
lav_mvn_cl_rs_em_h0() EM: the driver
lav_mvn_cl_rs_scaling_h0() the scaling factor of Equation 16.25
lav_mvn_cl_rs_eb() the predictions (empirical Bayes)
lav_mvn_cl_rs_eb_nl() the predictions with latent covariates