This appendix collects the derivations behind the two-level random-intercept model of chapter 16: the reduction of the per-cluster log-likelihood to expressions in P \times P matrices, the EM algorithm for the unrestricted (\mathsf{H}_1) model with complete and with incomplete data, the observed information matrix by Louis’s identity, and the predictions of the cluster-level unknowns. A final section (Section E.7) does the same for the two-level model with random slopes of Section 16.13. Only the key steps and the final formulas are given; the matrix identities used along the way (the inverse and determinant of a partitioned matrix, the Woodbury identity, the vec and Kronecker rules) are collected in appendix B. The main references are McDonald and Goldstein (1989) and Muthén (1990) for the complete-data likelihood, Dempster et al. (1977) for the EM algorithm, and Louis (1982) for the observed information. The notation follows Section 16.3. The routines of the current R implementation that evaluate these expressions are named in the function map of chapter 16 (Section 16.15.2).
E.1 Notation and the per-cluster distribution
There are N_J clusters; cluster j contains n_j level-1 units, and N= \sum_j n_j is the total number of units. The P \times 1 vector \mathbf{y}_{ji} collects the level-1 variables of unit i in cluster j (the shared and the within-only variables), and the P_z \times 1 vector \mathbf{z}_j the between-only variables of the cluster. Every level-1 observation is the sum of a cluster-level component and a unit-level component,
with all components independent. The between component \boldsymbol{\nu}_j is the random intercept of cluster j (in the notation of Equation 16.1, \boldsymbol{\mu}+ \mathbf{y}_{B,j}), and the total mean of a level-1 variable is \boldsymbol{\mu}_y = \boldsymbol{\mu}_W + \boldsymbol{\mu}_B. For the shared variables, \boldsymbol{\mu}_W = \mathbf{0} and the mean is modeled at the between level (Section 16.4.3); \boldsymbol{\mu}_W is nonzero only for variables with a within-level mean structure. The between-only variables are jointly normal with the between component, with mean \boldsymbol{\mu}_z and covariance blocks \boldsymbol{\Sigma}_{zz} and \boldsymbol{\Sigma}_{zy} = \boldsymbol{\Sigma}_{yz}^{\prime}. These four mean vectors and covariance matrices (\boldsymbol{\mu}_W, \boldsymbol{\Sigma}_W, \boldsymbol{\mu}_B, \boldsymbol{\Sigma}_B, the latter two extended by the z blocks) are the “2l” representation of the implied moments in Section 16.15.1.
Stack the data of cluster j into the vector \mathbf{v}_j = (\mathbf{z}_j^{\prime}, \mathbf{y}_{j1}^{\prime}, \ldots,
\mathbf{y}_{jn_j}^{\prime})^{\prime} of length P_z + n_j P. Its mean is (\boldsymbol{\mu}_z^{\prime}, \mathbf{1}_{n_j}^{\prime} \otimes
\boldsymbol{\mu}_y^{\prime})^{\prime}, and its covariance matrix is
Evaluating Equation E.3 as it stands requires the inverse and the determinant of a matrix of order P_z + n_j P for every cluster. The next section shows that both reduce to P \times P quantities.
E.2 The log-likelihood in P \times P terms
Three steps are needed. Throughout, let \boldsymbol{\Sigma}_{B \cdot z} = \boldsymbol{\Sigma}_B - \boldsymbol{\Sigma}_{yz}\boldsymbol{\Sigma}_{zz}^{-1}\boldsymbol{\Sigma}_{zy} be the between covariance matrix conditional on the between-only variables (equal to \boldsymbol{\Sigma}_B when there are none), and
The inverse. Apply the partitioned-inverse identity to Equation E.2. The Schur complement of \boldsymbol{\Sigma}_{zz} is \mathbf{I}_{n_j} \otimes \boldsymbol{\Sigma}_W + \mathbf{1}_{n_j}\mathbf{1}_{n_j}^{\prime} \otimes \boldsymbol{\Sigma}_{B \cdot z}, a matrix of the form “identity-Kronecker plus rank-one-Kronecker” whose inverse follows from the Woodbury identity:
The remaining blocks of \mathbf{V}_j^{-1} follow from the same identity and collapse, after the Kronecker products are multiplied out, to -\boldsymbol{\Sigma}_{zz}^{-1}\bigl[\mathbf{1}_{n_j}^{\prime} \otimes
\boldsymbol{\Sigma}_{zy}\boldsymbol{\Sigma}_j^{-1}\bigr] for the off-diagonal block and \boldsymbol{\Sigma}_{zz}^{-1} + n_j\,\boldsymbol{\Sigma}_{zz}^{-1}\boldsymbol{\Sigma}_{zy}\boldsymbol{\Sigma}_j^{-1}
\boldsymbol{\Sigma}_{yz}\boldsymbol{\Sigma}_{zz}^{-1} for the z block. Only P \times P and P_z \times P_z inverses appear.
The quadratic form. Substituting the blocks into Equation E.3 and using the vec and trace rules (\mathrm{tr}(\mathbf{A}\mathbf{B}) = \mathrm{vec}(\mathbf{A}^{\prime})^{\prime}
\mathrm{vec}(\mathbf{B}) and \mathrm{vec}(\mathbf{A}\mathbf{X}\mathbf{B})
= (\mathbf{B}^{\prime} \otimes \mathbf{A})\mathrm{vec}(\mathbf{X})), every term becomes the trace of a P \times P product. The terms that involve \mathbf{I}_{n_j} \otimes \boldsymbol{\Sigma}_W^{-1} produce the within-cluster scatter matrix \mathbf{A}_j = \sum_i (\mathbf{y}_{ji} - \bar{\mathbf{y}}_j)
(\mathbf{y}_{ji} - \bar{\mathbf{y}}_j)^{\prime}, and all terms that involve \mathbf{1}_{n_j}\mathbf{1}_{n_j}^{\prime} depend on the data only through the cluster mean \bar{\mathbf{y}}_j. Collecting the latter with the z terms, the quadratic form becomes
where \bar{\mathbf{v}}_j = (\mathbf{z}_j^{\prime}, \bar{\mathbf{y}}_j^{\prime})^{\prime} is the vector of cluster-level data, \boldsymbol{\mu}_b = (\boldsymbol{\mu}_z^{\prime},
\boldsymbol{\mu}_y^{\prime})^{\prime} its mean, and
its covariance matrix: the cluster mean of n_j units has covariance \boldsymbol{\Sigma}_B + \boldsymbol{\Sigma}_W/n_j, and it covaries with \mathbf{z}_j through \boldsymbol{\Sigma}_{yz}. The Schur complement of \boldsymbol{\Sigma}_{zz} in \mathbf{M}_j is \boldsymbol{\Sigma}_j / n_j, so the inverse of \mathbf{M}_j again involves only \boldsymbol{\Sigma}_j^{-1} and \boldsymbol{\Sigma}_{zz}^{-1}.
The determinant. By the partitioned-determinant identity and a recursion over the units (McDonald & Goldstein, 1989),
Without between-only variables, \mathbf{M}_j = \boldsymbol{\Sigma}_j / n_j, the quadratic form reduces to n_j (\bar{\mathbf{y}}_j - \boldsymbol{\mu}_y)^{\prime}
\boldsymbol{\Sigma}_j^{-1}(\bar{\mathbf{y}}_j - \boldsymbol{\mu}_y), and Equation E.9 is Equation 16.8. Summing over clusters, the within terms combine into (N- N_J)\{\ln|\boldsymbol{\Sigma}_W| + \mathrm{tr}[\boldsymbol{\Sigma}_W^{-1}
\mathbf{S}_{PW}]\} with the pooled within covariance matrix \mathbf{S}_{PW} of Equation 16.9, and the between terms depend on j only through n_j, so that clusters of equal size can be pooled (Equation 16.10). This is the form given by Muthén (1990); lavaan evaluates the equivalent per-stratum expression in terms of \boldsymbol{\Sigma}_{zz}, \boldsymbol{\Sigma}_{B \cdot z}, and \boldsymbol{\Sigma}_j, without forming \mathbf{M}_j. The following chunk evaluates Equation E.9 cluster by cluster at the unrestricted estimates and compares the sum with the unrestricted log-likelihood reported by lavaan:
formula lavaan.unrestricted.logl
-12513.7 -12513.7
E.3 The EM algorithm for the unrestricted model
The unrestricted model leaves \boldsymbol{\mu}_W, \boldsymbol{\Sigma}_W, \boldsymbol{\mu}_B, \boldsymbol{\Sigma}_B (and the z blocks) unrestricted. As explained in Section 16.6.1, its ML estimates have no closed form when the cluster sizes differ, and lavaan obtains them by an EM algorithm that treats the between components \boldsymbol{\nu}_j as missing data. Both steps of the algorithm follow from Equation E.1.
The complete-data log-likelihood. If the \boldsymbol{\nu}_j were observed, the data of cluster j would consist of n_j independent within components \mathbf{d}_{ji} = \mathbf{y}_{ji} - \boldsymbol{\nu}_j
\sim \mathcal{N}(\boldsymbol{\mu}_W, \boldsymbol{\Sigma}_W) and one between component \boldsymbol{\nu}_j \sim \mathcal{N}(\boldsymbol{\mu}_B, \boldsymbol{\Sigma}_B). Up to a constant, minus twice the complete-data log-likelihood of the cluster is
the sum of two ordinary normal log-likelihoods. Summed over clusters, the complete-data problem is a two-group model: one group of N within components and one group of N_J between components, without any coupling between them.
The E-step. The expectation of Equation E.10 given the observed data requires the posterior mean and covariance matrix of \boldsymbol{\nu}_j given \mathbf{y}_{j1}, \ldots, \mathbf{y}_{jn_j}, the rows of the n_j \times P data matrix \mathbf{Y}_j of the cluster. The two are jointly normal, with \mathrm{Cov}(\boldsymbol{\nu}_j,
\mathrm{vec}\,\mathbf{Y}_j^{\prime}) = \mathbf{1}_{n_j}^{\prime}
\otimes \boldsymbol{\Sigma}_B and the covariance matrix of the stacked \mathbf{y}_{ji} given by the lower-right block of Equation E.2. Applying Equation E.5 (with \boldsymbol{\Sigma}_{B \cdot z} = \boldsymbol{\Sigma}_B) and multiplying out the Kronecker products, the regression of \boldsymbol{\nu}_j on the stacked data simplifies to \mathbf{1}_{n_j}^{\prime} \otimes \boldsymbol{\Sigma}_B\boldsymbol{\Sigma}_j^{-1}, so that only the cluster mean enters:
with \boldsymbol{\Sigma}_j = \boldsymbol{\Sigma}_W + n_j \boldsymbol{\Sigma}_B (this is Equation 16.12). When between-only variables are present, \mathbf{z}_j joins the conditioning set: the same expressions hold with \boldsymbol{\Sigma}_B, \boldsymbol{\mu}_B, and \boldsymbol{\mu}_y replaced by their values conditional on \mathbf{z}_j. Writing \mathbf{m}_{bj} and \mathbf{C}_{bj} for the posterior mean and covariance matrix in Equation E.11, the expected sufficient statistics of the two groups are
where the posterior variance enters the within statistics because each within component is observed only up to the unknown \boldsymbol{\nu}_j. Pooled over clusters, with the within statistics weighted by n_j and the between statistics weighted equally, the expected complete-data log-likelihood becomes
with \bar{\mathbf{m}}_w and \bar{\mathbf{m}}_b the (weighted) averages of the cluster-level means, and \mathbf{C}_w and \mathbf{C}_b the corresponding pooled covariance matrices (the weighted averages of \mathbf{C}_{wj} + \mathbf{m}_{wj}\mathbf{m}_{wj}^{\prime} and \mathbf{C}_{bj} + \mathbf{m}_{bj}\mathbf{m}_{bj}^{\prime}, centered at \bar{\mathbf{m}}_w and \bar{\mathbf{m}}_b). Because Equation E.11 depends on j only through n_j and \bar{\mathbf{y}}_j, the E-step is carried out per cluster-size stratum, using the stratum statistics of Section 16.5.2; its cost is driven by the number of distinct cluster sizes.
The M-step. Expression Equation E.13 is the ML discrepancy of a two-group model with sample statistics (\bar{\mathbf{m}}_w,
\mathbf{C}_w) and (\bar{\mathbf{m}}_b, \mathbf{C}_b). For the unrestricted model, its minimizers are these statistics themselves:
(For a restricted model, the M-step would fit the two-group model to these statistics instead; this is the EM estimator for the \mathsf{H}_0 model of Section 16.7.2.) The moments of the between-only block do not depend on the unobserved components and are computed once, outside the iterations; within-level variances that collapse towards zero are floored at the min_variance value; the iterations are accelerated by SQUAREM (Varadhan & Roland, 2008) and stopped when the increase of the observed-data log-likelihood Equation E.9 drops below the tolerance (Section 16.6.3). The two steps are short enough to be written out in full; the following chunk implements them for the example above (complete data, no between-only variables) and compares the converged moments with the \mathsf{H}_1 solution of lavaan:
iterations within between mean
3.500000e+01 5.046949e-07 1.694960e-06 1.836921e-08
E.4 The EM algorithm with incomplete data
When some elements of the \mathbf{y}_{ji} are missing (assumed MAR), there are two layers of unobserved information: the between components \boldsymbol{\nu}_j, as before, and the missing elements \mathbf{y}_{ji[m]}, where [o] and [m] denote the observed and missing entries of a unit; units with the same observed set form a missing pattern. If both layers were known, the data would be complete, so the complete-data log-likelihood Equation E.10 and the M-step Equation E.14 are unchanged. Only the E-step changes: all expectations are now taken given the observed entries only. It is convenient to work with the centered between component \boldsymbol{\beta}_j = \boldsymbol{\nu}_j - \boldsymbol{\mu}_B \sim
\mathcal{N}(\mathbf{0}, \boldsymbol{\Sigma}_B), so that \mathbf{y}_{ji} = \boldsymbol{\mu}_y +
\boldsymbol{\beta}_j + \boldsymbol{\epsilon}_{ji} with \boldsymbol{\epsilon}_{ji} \sim \mathcal{N}(\mathbf{0}, \boldsymbol{\Sigma}_W).
Step 1: the posterior of the between component. Given \boldsymbol{\beta}_j, the units are independent, and the observed part of unit i is a marginal of a normal: \mathbf{y}_{ji[o]} \mid \boldsymbol{\beta}_j \sim
\mathcal{N}(\boldsymbol{\mu}_{y[o]} + \mathbf{S}_i\boldsymbol{\beta}_j, \boldsymbol{\Sigma}_{W,i}), with \boldsymbol{\Sigma}_{W,i} = [\boldsymbol{\Sigma}_W]_{[o,o]} the within covariance matrix of the observed entries of unit i, and \mathbf{S}_i the selection matrix of the observed rows. The matrix \boldsymbol{\Sigma}_{W,i} is the same for all units of a missing pattern r, and it is then written \boldsymbol{\Sigma}_{W,r}. Each unit contributes a normal likelihood term for \boldsymbol{\beta}_j; combined with the prior \mathcal{N}(\mathbf{0}, \boldsymbol{\Sigma}_B), standard Bayesian updating gives the posterior (with \mathbf{Y}_j^{obs} the observed entries of the cluster) \boldsymbol{\beta}_j \mid \mathbf{Y}_j^{obs} \sim
\mathcal{N}(\mathbf{m}_{1j}, \mathbf{C}_{1j}) with
The form based on \mathbf{I} + \boldsymbol{\Sigma}_B\mathbf{Q}_j avoids inverting \boldsymbol{\Sigma}_B and remains valid when \boldsymbol{\Sigma}_B is singular (variables without a between component); the same matrix appears in the two-level FIML log-likelihood with missing data. With complete data, \boldsymbol{\Sigma}_{W,i} = \boldsymbol{\Sigma}_W and \mathbf{S}_i =
\mathbf{I}, so \mathbf{Q}_j = n_j\boldsymbol{\Sigma}_W^{-1} and \mathbf{p}_j =
n_j\boldsymbol{\Sigma}_W^{-1}(\bar{\mathbf{y}}_j - \boldsymbol{\mu}_y), and Equation E.15 reduces to Equation E.11.
Step 2: the missing elements within a unit. Given \boldsymbol{\beta}_j and the observed part of the same unit, the missing part follows the usual conditional-normal expressions; per pattern r only two matrices are needed,
so that \mathrm{E}[\mathbf{y}_{ji[m]} \mid \boldsymbol{\beta}_j, \mathbf{y}_{ji[o]}]
= \boldsymbol{\mu}_{y[m]} + \boldsymbol{\beta}_{j[m]} + \mathbf{B}_r(\mathbf{y}_{ji[o]}
- \boldsymbol{\mu}_{y[o]} - \boldsymbol{\beta}_{j[o]}) with conditional covariance \mathbf{C}_r. The other units of the cluster inform \mathbf{y}_{ji[m]} only through \boldsymbol{\beta}_j, so that the computations remain at the P \times P level.
The E-step statistics. Write the within residual as an affine function of \boldsymbol{\beta}_j plus independent noise: for the observed rows, \mathbf{d}_{ji[o]} = \mathbf{y}_{ji[o]} - \boldsymbol{\mu}_{B[o]} -
\boldsymbol{\beta}_{j[o]}; for the missing rows, substituting the Step 2 expression, the \boldsymbol{\beta}_{j[m]} terms cancel and \mathbf{d}_{ji[m]} = \boldsymbol{\mu}_{W[m]} + \mathbf{B}_r(\mathbf{y}_{ji[o]} -
\boldsymbol{\mu}_{y[o]} - \boldsymbol{\beta}_{j[o]}) + \boldsymbol{\epsilon}^{\ast} with \boldsymbol{\epsilon}^{\ast} \sim \mathcal{N}(\mathbf{0},
\mathbf{C}_r). Taking expectations with \mathbf{f}_{ji} =
\mathbf{y}_{ji[o]} - \boldsymbol{\mu}_{y[o]} - \mathbf{m}_{1j[o]},
with \mathbf{G} = \mathbf{S}_i\mathbf{C}_{1j}\mathbf{S}_i^{\prime} the observed block of the posterior variance (rows and columns ordered as observed, missing), and \mathrm{E}[\mathbf{d}_{ji}\mathbf{d}_{ji}^{\prime}]
= \mathrm{E}[\mathbf{d}_{ji}]\mathrm{E}[\mathbf{d}_{ji}]^{\prime} +
\mathrm{Var}(\mathbf{d}_{ji}). The covariance is the same for all units that share a pattern and a cluster, and the per-pattern quantities \boldsymbol{\Sigma}_{W,r}^{-1}, \mathbf{B}_r, \mathbf{C}_r are computed once per iteration, which keeps the E-step inexpensive. Units with all variables missing contribute \mathrm{E}[\mathbf{d}_{ji}] = \boldsymbol{\mu}_W and \mathrm{Var}(\mathbf{d}_{ji}) = \boldsymbol{\Sigma}_W. The between statistics follow from Step 1: \mathrm{E}[\boldsymbol{\nu}_j] = \boldsymbol{\mu}_B +
\mathbf{m}_{1j} and \mathrm{E}[\boldsymbol{\nu}_j\boldsymbol{\nu}_j^{\prime}]
= \mathbf{C}_{1j} + \mathrm{E}[\boldsymbol{\nu}_j]\mathrm{E}[\boldsymbol{\nu}_j]^{\prime}. The M-step is Equation E.14 applied to these expected statistics.
Between-only variables. When between-only variables are present, possibly with missing values themselves, the cluster-level unknowns are \mathbf{u}_j = (\boldsymbol{\beta}_j, \tilde{\mathbf{z}}_{j[m]}) with \tilde{\mathbf{z}}_j = \mathbf{z}_j - \boldsymbol{\mu}_z. Conditioning the joint prior of (\boldsymbol{\beta}_j, \tilde{\mathbf{z}}_j) on the observed \tilde{\mathbf{z}}_{j[o]} gives a prior \mathcal{N}(\mathbf{m}_{0j},
\mathbf{C}_0) that depends only on the missing pattern of \mathbf{z}_j. Since the level-1 data inform only \boldsymbol{\beta}_j, the posterior follows from the same update as in Step 1, with \tilde{\mathbf{Q}}_j =
\mathrm{blkdiag}(\mathbf{Q}_j, \mathbf{0}) and \tilde{\mathbf{p}}_j =
(\mathbf{p}_j, \mathbf{0}):
again valid for singular \mathbf{C}_0. The posterior moments of \mathbf{u}_j supply the expected statistics for \boldsymbol{\mu}_z, \boldsymbol{\Sigma}_{zz}, and \boldsymbol{\Sigma}_{yz} in the M-step.
The observed-data log-likelihood as a by-product. The EM iterations need the observed-data log-likelihood to monitor progress and to stop. Evaluating it with the generic FIML routine costs a second pass over all patterns and clusters, duplicating work the E-step has just done. Instead, the likelihood of a cluster can be factored into the marginal of the observed between-only variables and a Gaussian integral over \mathbf{u}_j whose exponent is quadratic with precision \mathbf{C}_0^{-1} + \tilde{\mathbf{Q}}_j and mean \mathbf{m}_{1j}, the quantities of Equation E.18. Completing the square and evaluating the integral gives, in a form that does not require \mathbf{C}_0^{-1},
so that -2\log L^{obs} equals the sum over units of the per-pattern log-determinants \ln|\boldsymbol{\Sigma}_{W,r}| and quadratic forms of the observed residuals, the corresponding terms for the observed between-only variables, and \sum_j (-2\log I_j), plus the constant. Every term is available when the E-step finishes; the only extra cost is one small determinant per cluster. The value is the log-likelihood at the parameter values at which the E-step was evaluated, one iteration behind the M-step update, which the implementation accounts for by looking one step ahead. The fused element of em_h1_args selects this route (the current default) or the stand-alone evaluation.
This algorithm is the default for the \mathsf{H}_1 model with two-level incomplete data (h1_missing_method = "em"; see Section 16.9). The matrices \mathbf{Q}_j and \mathbf{p}_j are the ones that appear in the two-level FIML log-likelihood, and the pattern inverses \boldsymbol{\Sigma}_{W,r}^{-1} are obtained from \boldsymbol{\Sigma}_W^{-1} by symmetric inverse updates. The resulting moments and \mathsf{H}_1 log-likelihood match the estimated sample statistics reported by Mplus.
E.5 The observed information by Louis’s identity
Standard errors and robust test statistics need the observed information matrix, minus the Hessian of the observed-data log-likelihood \ell(\boldsymbol{\vartheta}). Numerical differentiation of the analytic gradient requires four full passes over the data per free parameter, and the result is not exactly symmetric. Louis (1982) showed that the observed information can be computed from quantities the E-step already delivers:
where \ell^{c} is the complete-data log-likelihood and the expectations are over the posterior of the unobserved quantities given the observed data, at the same \boldsymbol{\vartheta}. The identity follows from writing \ell = \log\int
e^{\ell^{c}}\,d\mathbf{Y}^{mis} (with \mathbf{Y}^{obs} the observed data and \mathbf{Y}^{mis} all the unobserved quantities) and differentiating twice: the first derivative gives Fisher’s identity, \partial\ell/\partial\boldsymbol{\vartheta}=
\mathrm{E}[\partial \ell^{c}/\partial\boldsymbol{\vartheta}\mid \mathbf{Y}^{obs}] (the observed-data score is the posterior expectation of the complete-data score), and the second derivative adds, through the dependence of the posterior density on \boldsymbol{\vartheta}, the posterior variance of the complete-data score. The interpretation is the missing-information principle: the less certain the posterior of the unobserved quantities, the larger the covariance term and the more information is lost relative to complete data.
For the two-level model, the unobserved quantities are the between components, the missing level-1 values, and the missing between-only values; the complete-data model is the two-group model of Section E.3, so the first term of Equation E.20 is the information matrix of a two-group SEM evaluated at the expected sufficient statistics, which requires one additional E-step at the final estimates. The second term is a sum over clusters, because clusters are independent given the observed data. Within cluster j, conditioning on the cluster-level unknowns \mathbf{u}_j = (\boldsymbol{\beta}_j,
\tilde{\mathbf{z}}_{j[m]}), whose posterior \mathcal{N}(\mathbf{m}_{1j},
\mathbf{C}_{1j}) the E-step computes, and applying the law of total covariance splits the term into two parts. The within-noise part is the expected conditional variance: given \mathbf{u}_j, only the conditional noise of the missing values remains random, the units are conditionally independent, and each unit’s score is a linear (mean) and quadratic (covariance) function of a normal vector, so the standard moment results for \mathbf{x} \sim \mathcal{N}(\mathbf{c}, \mathbf{V}),
with \mathbf{K} the commutation matrix, suffice; because the conditional noise covariance is constant within a pattern, everything aggregates pattern-wise. The between part is the covariance of the conditional expectation, a quadratic polynomial in the centered posterior variable \tilde{\mathbf{u}}_j \sim \mathcal{N}(\mathbf{0},
\mathbf{C}_{1j}), for which linear and quadratic parts are uncorrelated and
The same computation yields the expected complete-data score as a by-product, which by Fisher’s identity must equal the observed-data gradient computed independently; this check holds to machine precision and is used as an internal test. Finally, the chain rule maps the moment-level result to the model parameters: the covariance term is pre- and post-multiplied by the Jacobian \boldsymbol{\Delta} of the four moment blocks with respect to \boldsymbol{\vartheta}, and the complete-information term is obtained by differentiating the complete-data gradient, a function of the implied moments and the fixed expected statistics only, so that no further passes over the data are needed.
Two details matter in the implementation. The complete-data model has one within term per level-1 unit including units for which all level-1 variables are missing, so the number of within terms can exceed the number of observations used elsewhere. In addition, two mean conventions coexist. In the formulas above, the expected between component is \boldsymbol{\mu}_B + \mathbf{m}_{1j}. The implementation stores it on the scale of the total mean, \boldsymbol{\mu}_y + \mathbf{m}_{1j}, while the complete-data score is naturally written in the implied convention with a possibly nonzero \boldsymbol{\mu}_W; the score vector is the same under both, but the expected means differ by the fixed shift \boldsymbol{\mu}_W, which only matters in models with within-level covariates. The identity is used for two-level models with missing = "ml"; the result matches the numerical Hessian to about six digits, is symmetric by construction, and is obtained roughly ten to twenty times faster for models with fifteen to twenty free parameters. If the computation fails for a particular model, lavaan falls back to the numerical Hessian.
The scaled test statistics also need the observed information of the unrestricted model, where the parameters are the moments themselves (\boldsymbol{\mu}_W, \mathrm{vech}\,\boldsymbol{\Sigma}_W, \boldsymbol{\mu}_B, \mathrm{vech}\,\boldsymbol{\Sigma}_B). The identity applies in the same way, and more simply, because no chain rule is needed: the first term of Equation E.20 is the observed information of two independent normal samples (the level-1 units and the clusters), evaluated at the expected complete-data moments of one E-step, and the second term is the moment-level covariance derived above, without the Jacobian \boldsymbol{\Delta}. For the shared variables, only the sum of the within and the between mean is a parameter of the unrestricted model (it is stored in \boldsymbol{\mu}_B), so the columns of their within means are set to zero. The numerical alternative differentiates the missing-data gradient once per unrestricted moment, which becomes very slow with many variables or clusters; it is kept as a fallback only.
E.6 Predictions
After estimation, three kinds of cluster- and unit-level predictions are of interest: the between components \boldsymbol{\nu}_j (the random effects), the factor scores at both levels, and, with incomplete data, the missing values themselves. All three are functions of quantities whose posterior distribution given all the observed data the E-step already computes.
Random effects. From Equation E.18, the posterior of \boldsymbol{\nu}_j has mean \boldsymbol{\mu}_B + \mathbf{m}_{1j[\beta]} and covariance \mathbf{C}_{1j[\beta,\beta]}; it conditions on the observed parts of every unit and on the observed between-only variables. With complete data, it reduces to the classical predictor \boldsymbol{\mu}_B + n_j\boldsymbol{\Sigma}_B\boldsymbol{\Sigma}_j^{-1}(\bar{\mathbf{y}}_j - \boldsymbol{\mu}_y) of Equation E.11, evaluated at the model-implied moments of the fitted model. This is what lavInspect(fit, "ranef") returns:
Imputations. The conditional mean of the missing values of unit ji given \boldsymbol{\beta}_j and the unit’s observed part (Step 2 above) is linear in \boldsymbol{\beta}_j, so replacing \boldsymbol{\beta}_j by its posterior mean gives the exact posterior mean of the missing values given all observed data (the tower property); missing between-only values are imputed by \boldsymbol{\mu}_{z[m]} +
\mathbf{m}_{1j[z]}.
Factor scores. For two-level models, the level-1 scores are obtained by applying the factor-score coefficient matrix of the within model to the within-centered data \mathbf{y}_{ji} - \hat{\boldsymbol{\nu}}_j, and the level-2 scores by applying that of the between model to the cluster-level data (\hat{\boldsymbol{\nu}}_j, \mathbf{z}_j) (Section 13.3.10). The whole map from the complete data to the scores is linear, so replacing the unobserved quantities (missing values, between components, missing between-only values) by their posterior means and then applying the complete-data expressions yields exactly the posterior mean of the complete-data factor scores given all observed data. The standard errors of the scores, however, are computed from the complete-data expressions and ignore the uncertainty in \hat{\boldsymbol{\nu}}_j and in the imputed values; they are best regarded as lower bounds. The posterior computations are shared with the Louis computation, and the same E-step computations give the random effects, optionally with their posterior standard deviations and the posterior-mean completed data; lavPredict() and lavInspect(fit, "ranef") use this route for two-level models with missing = "ml".
E.7 Random slopes
This section collects the computational details behind the two-level model with random slopes of Section 16.13. The notation is that of Section 16.13.5: \mathbf{u}_j is the vector of cluster-level random variables, with mean \boldsymbol{\mu}_{u,j} and covariance matrix \boldsymbol{\Sigma}_u (Equation 16.16), and the outcomes of unit i in cluster j have mean \boldsymbol{\mu}_y + \boldsymbol{\Pi}\,\mathbf{x}_{ji} + \mathbf{Q}_{ji}\,
\mathbf{u}_j and covariance matrix \boldsymbol{\Sigma}_W, given \mathbf{u}_j (Equation 16.17). Throughout this section, \mathbf{W} = \boldsymbol{\Sigma}_W^{-1} is the within precision matrix. A few other symbols also have a meaning that differs from the one in the preceding sections: \mathbf{u}_j (defined above), \mathbf{Q}_j (the stacked design matrix of the random effects) and \mathbf{G} (a matrix of between-level loadings). The main reference is Rockwood (2020), for the observed-data likelihood and the extension to latent covariates; the EM algorithm follows the general scheme of Dempster et al. (1977), with the cluster-level random effects as the missing data (Laird & Ware, 1982; Liang & Bentler, 2004).
E.7.1 The log-likelihood of a cluster
The stacked outcomes \mathbf{y}_j of a cluster have covariance matrix \mathbf{V}_j = \mathbf{I}_{n_j} \otimes \boldsymbol{\Sigma}_W + \mathbf{Q}_j
\boldsymbol{\Sigma}_u \mathbf{Q}_j^{\prime} (Equation 16.19). With \mathbf{H}_j = \mathbf{Q}_j^{\prime}(\mathbf{I}_{n_j} \otimes \mathbf{W})
\mathbf{Q}_j, the Woodbury identity and the matrix determinant lemma give, for a nonsingular \boldsymbol{\Sigma}_u,
The inverse of \boldsymbol{\Sigma}_u is removed by the identity (\boldsymbol{\Sigma}_u^{-1} + \mathbf{H}_j)\boldsymbol{\Sigma}_u = \mathbf{I} +
\mathbf{H}_j\boldsymbol{\Sigma}_u, which gives
and the right-hand sides remain valid when \boldsymbol{\Sigma}_u is singular (by continuity). Substituting them in the normal log-density of \mathbf{y}_j gives Equation 16.21. The matrix \mathbf{I} +
\mathbf{H}_j\boldsymbol{\Sigma}_u is of order K and not symmetric; its determinant and the solution of the linear system are obtained from an LU decomposition. The inverse-free form matters in practice. Between-level variances are often fixed to zero, or estimated at (or below) zero, and the version with \boldsymbol{\Sigma}_u^{-1} makes the objective function jump to infinity at such a boundary, where an optimizer then fails. In the form used here, the only requirement is that every \mathbf{V}_j is positive definite. If \boldsymbol{\Sigma}_u is positive semidefinite, this is guaranteed, and |\mathbf{I} + \mathbf{H}_j\boldsymbol{\Sigma}_u| > 0; if \boldsymbol{\Sigma}_u is indefinite, the eigenvalues of \mathbf{I} + \mathbf{H}_j\boldsymbol{\Sigma}_u (which are real) must all be positive, and the objective function is set to infinity otherwise.
E.7.2 Per-cluster cross-products
Write \mathbf{e}_{ji} = \mathbf{y}_{ji} - \boldsymbol{\mu}_y - \boldsymbol{\Pi}\,
\mathbf{x}_{ji} for the residual of a unit before the cluster-level part is subtracted, and define the uncentered versions of the score and the sum of squares of Equation 16.20,
so that \mathbf{g}_j = \mathbf{g}_j^{0} - \mathbf{H}_j\boldsymbol{\mu}_{u,j} and c_j = c_j^{0} - 2\boldsymbol{\mu}_{u,j}^{\prime}\mathbf{g}_j^{0} +
\boldsymbol{\mu}_{u,j}^{\prime}\mathbf{H}_j\boldsymbol{\mu}_{u,j}. Because \mathbf{Q}_{ji} = \mathbf{Q}_0 + \sum_r x_{ji}^{(r)}\boldsymbol{\lambda}_r
\mathbf{e}_{k(r)}^{\prime} (Equation 16.18, with \mathbf{e}_{k(r)} a unit vector) and the residuals \mathbf{e}_{ji} are linear in the data of the unit, the sums over the units of a cluster depend on the data only through the cross-products
which are computed once, before the optimization starts. Writing s^{x(r)}_j and \mathbf{S}^{xx}_{j[r,r']} for the elements that belong to the covariates of the random-slope regressions r and r', and \mathbf{U}_j = \sum_r s^{x(r)}_j\,\boldsymbol{\lambda}_r
\mathbf{e}_{k(r)}^{\prime}, we have
The matrices that do not depend on the cluster (\mathbf{Q}_0^{\prime}\mathbf{W}\mathbf{Q}_0, \mathbf{Q}_0^{\prime}\mathbf{W}\boldsymbol{\lambda}_r, \boldsymbol{\lambda}_r^{\prime}\mathbf{W}\boldsymbol{\lambda}_{r'}, \mathbf{W}\boldsymbol{\Pi}, and similar products) are computed once per evaluation. The cost of an evaluation of the log-likelihood is therefore of the order N_J (P + K)^3, regardless of the cluster sizes; after the initial pass over the data, there are no loops over the units. These cross-products play the role that the pooled within matrix and the cluster means play in the random-intercept model.
E.7.3 Between-only endogenous variables
Between-only endogenous variables \mathbf{z}_j (the indicators of a between-level factor) are observed once per cluster. Given \mathbf{u}_j, they are one more independent normal observation of the cluster, next to its n_j units:
where \mathbf{G} contains the between-level loadings of these variables (and zeros in the columns of the between residuals of the shared variables), \boldsymbol{\mu}_z their intercepts, and \boldsymbol{\Sigma}_z their block of \boldsymbol{\Theta}_B. Completing the square in \mathbf{u}_j shows that each of the three quantities of the cluster receives an extra term, with \mathbf{e}_{zj} = \mathbf{z}_j - \boldsymbol{\mu}_z:
and \ln|\boldsymbol{\Sigma}_z| + P_z\ln(2\pi) is added to the constant of the cluster. Everything else is unchanged. This formulation requires a positive definite \boldsymbol{\Sigma}_z, which is why these variables must have a residual variance that is not fixed to zero.
E.7.4 Missing data
With missing = "ml", a unit contributes the subset of its outcomes that is observed. Given \mathbf{u}_j, the units are independent, so that deleting the missing elements of a unit only changes its weight matrix. For a missing-data pattern with observed elements o, let \mathbf{W}_o be the P \times P matrix that contains [\boldsymbol{\Sigma}_W]_{[o,o]}^{-1} in the rows and columns of the observed elements, and zeros elsewhere. The expressions of Equation E.23 then hold for each combination of a cluster and a pattern, with \mathbf{W} replaced by \mathbf{W}_o and the missing values replaced by zeros in the cross-products: the zero rows and columns of \mathbf{W}_o remove exactly the terms that involve a missing value. The quantities \mathbf{H}_j, \mathbf{g}_j^{0} and c_j^{0} of a cluster are the sums over the patterns that occur in the cluster, the term n_j \ln|\boldsymbol{\Sigma}_W| becomes a sum of \ln|[\boldsymbol{\Sigma}_W]_{[o,o]}| over the units, and the integration over \mathbf{u}_j proceeds as before. The covariates must be complete: a unit with a missing covariate has no conditional likelihood, and is removed. A unit of which all outcomes are missing carries no information and is removed as well.
E.7.5 The analytic gradient
The model parameters enter the log-likelihood only through the vector of ingredients
and the gradient is computed in two layers, as the product of the derivatives of the log-likelihood with respect to \boldsymbol{\varphi} and the Jacobian \partial\boldsymbol{\varphi}/\partial\boldsymbol{\vartheta}^{\prime}. For the first layer, write F_j = -2\log L_j (without the constant), and consider it first as a function of the quantities of the cluster. With the posterior moments of Equation 16.22 and \mathbf{M}_{u \mid j} =
\boldsymbol{\Sigma}_{u \mid j} + \boldsymbol{\mu}_{u \mid j}\boldsymbol{\mu}_{u \mid j}^{\prime}, the derivatives are
together with a similar expression for \boldsymbol{\Sigma}_u. The derivative with respect to the information matrix \mathbf{H}_j is the posterior second moment of the random effects, and the derivative with respect to the score is (minus twice) their posterior mean. This is an instance of Fisher’s identity: the gradient of the observed-data log-likelihood is the posterior expectation of the gradient of the complete-data log-likelihood, so that the derivatives must be the statistics of the E-step below. These derivatives are then passed on to the elements of \boldsymbol{\varphi} through Equation E.23, which again involves only the per-cluster cross-products; the cost of the first layer is that of one evaluation of the log-likelihood. The second layer, the Jacobian of \boldsymbol{\varphi}, does not involve the data: it is the derivative of a few products of small model matrices, and it is computed by central differences in the current implementation. If the derivatives of the first layer are kept per cluster instead of being summed, the same computation gives the cluster scores \mathbf{s}_j that the sandwich estimator of Equation 16.24 and the scaling factor of Equation 16.25 need.
E.7.6 The EM algorithm
The EM algorithm treats the cluster-level vector \mathbf{u}_j as the missing data, as is common for mixed models (Laird & Ware, 1982) and for two-level structural equation models (Liang & Bentler, 2004); the within-level latent variables are not completed, and stay inside \boldsymbol{\Sigma}_W(\boldsymbol{\vartheta}). If \mathbf{u}_j were observed, two quantities would be known for every unit: the outcome minus its cluster-level part, and, for each random slope, the product of the slope of the cluster and the covariate value of the unit,
where \boldsymbol{\mu}_B contains, in this section, the between-level intercepts of the shared variables. The product \zeta_{ji,r} is all that a regression with a random slope contributes to the within part of a unit: where the definition-variable approach represents a random slope as a factor whose loading is the covariate value of the unit (Mehta & Neale, 2005), here the slope is known, the product is an ordinary variable, and its regression coefficient is one. With these complete data, the model separates into two ordinary structural equation models. Given the \boldsymbol{\zeta}_{ji}, the vectors \mathbf{y}^{W}_{ji} are independent across all N units and follow the within model, in which each regression with a random slope is replaced by a regression on the variable \zeta_{ji,r} with a coefficient fixed to one. For each cluster, the between-level vector consists of the between components of the shared variables, the random slopes, and the covariates \mathbf{w}_j; these vectors are independent across the N_J clusters and follow the between model, in which the random slopes are observed variables.
The within part of the complete-data log-likelihood is thus a conditional one: the log-likelihood of the \mathbf{y}^{W}_{ji} given the \boldsymbol{\zeta}_{ji}. To fit it with the routines for an ordinary (joint) model, we use the fact that a conditional log-likelihood is a joint log-likelihood minus a marginal one,
and that this holds for any choice of the marginal distribution of \boldsymbol{\zeta}_{ji}. As long as this distribution does not contain free parameters, the last term is a constant in the M-step, and maximizing the joint log-likelihood is the same as maximizing the conditional one. The same reasoning is behind the treatment of exogenous covariates as fixed: their marginal distribution carries no model parameters. The simplest choice is taken: in the within model, the variables \zeta_{ji,r} have zero means, unit variances and zero covariances, all fixed.
In the E-step, the posterior moments \boldsymbol{\mu}_{u \mid j} and \mathbf{M}_{u \mid j} of every cluster are computed from Equation 16.22, and the expected sums of the first and second moments of the complete data follow from them and the cross-products of Equation E.22. With \mathbf{a}_{ji} = \mathbf{y}_{ji} - \boldsymbol{\mu}_B,
The between-level vector is a linear function of \mathbf{u}_j and \mathbf{w}_j, so that its expected moments follow directly from \boldsymbol{\mu}_{u \mid j} and \mathbf{M}_{u \mid j}. Summing over the clusters gives a mean vector and a covariance matrix for a within group of size N and for a between group of size N_J. The M-step maximizes the expected complete-data log-likelihood, which is the log-likelihood of a two-group single-level model fitted to these moments, as in Section 16.7.2. Its parameter table is derived from the two-level one: in the within group, the covariates with a random slope are replaced by the variables \zeta_r, with fixed unit coefficients, unit variances, and zero means and covariances; in the between group, the rows that declare the random slopes as latent variables are removed, so that they become observed. All added and removed rows are fixed, and the free parameters of the two-group model are those of the two-level model, in the same order. The M-step is an iterative fit, started at the current values, and not a closed-form update. With missing outcomes, the E-step also completes the missing values of each unit, given \mathbf{u}_j and its observed outcomes; the M-step is unchanged.
Each EM cycle increases the observed-data log-likelihood of Equation 16.21, and the acceleration schemes, the offset for variances that are fixed to zero, and the final quasi-Newton run of Section 16.7.2 apply. The two-group device cannot accommodate a fixed effect of a covariate that also carries a random slope (\boldsymbol{\Pi} \neq \mathbf{0} for such a covariate), for a random slope that is shared by several regressions, or for between-only endogenous variables; in these cases, and for random slopes with latent covariates, the quasi-Newton optimizer is used.
E.7.7 Quadrature for latent covariates
Partition \mathbf{u}_j into the slopes \mathbf{u}_{s} that multiply a latent covariate and the remaining (linear) part \mathbf{u}_{l}, with the corresponding partition of \boldsymbol{\mu}_{u,j} and \boldsymbol{\Sigma}_u. Fixing \mathbf{u}_{s} = \mathbf{b} has two effects. In the within model, the slopes are now known numbers: they are written into their cells of \mathbf{B}_W, and the ingredients \boldsymbol{\Sigma}_W(\mathbf{b}), \boldsymbol{\lambda}_r(\mathbf{b}), \boldsymbol{\Pi}(\mathbf{b}) and \boldsymbol{\mu}_y(\mathbf{b}) are computed as before. The latent covariate remains an ordinary within-level factor, and its variance now reaches the outcomes through the slope. In the between model, the linear part has the conditional distribution
with a covariance matrix that is the same for all clusters and all values of \mathbf{b}. The conditional log-likelihood \log L_j(\mathbf{b}) is then Equation 16.21 for the reduced vector \mathbf{u}_{l}, computed from the same cross-products (Equation E.22). The marginal likelihood of Equation 16.23 is approximated with standard Gauss–Hermite nodes \mathbf{t}_d and weights \omega_d (a product rule over the dimensions), located at the prior distribution of the slopes: \mathbf{b}_d = \boldsymbol{\mu}_s + \mathbf{L}\mathbf{t}_d, where \mathbf{L}\mathbf{L}^{\prime} = \boldsymbol{\Sigma}_{ss} is a Cholesky factorization. The sum is computed in the log domain,
The nodes are not adapted to the clusters: the ingredients that depend on \mathbf{b} are then computed once per node instead of once per node and cluster, and with a single dimension of integration, adding nodes is the cheaper way to gain accuracy. Since the Cholesky factor locates the nodes, \boldsymbol{\Sigma}_{ss} must be positive definite; the tolerance for zero variances of the closed-form case applies to the linear part only.
If the slopes are predicted by cluster-level covariates, their prior mean \boldsymbol{\mu}_{s,j} differs across clusters. The nodes are still shared by all clusters, but the weights are corrected: for any set of nodes \mathbf{b}_d = \mathbf{c} + \mathbf{A}\mathbf{t}_d, adding
to the exponent of Equation E.27 gives an approximation of the same integral (a change of variables). The nodes are centered at the average of the prior means, and \mathbf{A}\mathbf{A}^{\prime} is the sum of \boldsymbol{\Sigma}_{ss} and the covariance matrix of the prior means over the clusters, so that the nodes cover the prior distribution of every cluster.
The derivative of Equation E.27 is a weighted sum of the derivatives of its terms, with the posterior probabilities of the nodes as weights,
where each term is obtained from the two-layer computation of the previous section, applied to the conditional model at node d; the dependence of the nodes themselves on the parameters is part of the Jacobian of the second layer. The same posterior probabilities give the predictions: the posterior distribution of \mathbf{u}_j is a mixture of the normal distributions of Equation 16.22 of the conditional models, and its mean is \sum_d \pi_{jd}\,\mathbf{b}_d for the slopes and \sum_d \pi_{jd}\,\boldsymbol{\mu}_{l \mid j}(\mathbf{b}_d) for the linear part.
E.7.8 Predictions
The predictions of the cluster-level variables are the posterior means \boldsymbol{\mu}_{u \mid j} of Equation 16.22, evaluated at the estimates, and their posterior standard deviations are the square roots of the diagonal elements of \boldsymbol{\Sigma}_{u \mid j}. For a model with a single outcome, these are the conditional modes and conditional variances of the linear mixed model. The elements that correspond to the between-level latent variables are returned, and they include the means: for a random slope, the prediction is the slope of the cluster, not its deviation from the mean slope.
For the within-level factor scores, the law of iterated expectations gives \mathrm{E}[\boldsymbol{\eta}_{W,ji} \mid \mathbf{y}_j] = \mathrm{E}\bigl[\mathrm{E}[\boldsymbol{\eta}_{W,ji}
\mid \mathbf{u}_j, \mathbf{y}_{ji}] \mid \mathbf{y}_j\bigr]: given \mathbf{u}_j, only the data of the unit itself matter. The inner expectation is a regression factor score of the within model, in which the mean of the outcomes is \boldsymbol{\mu}_y + \boldsymbol{\Pi}\,\mathbf{x}_{ji} +
\mathbf{Q}_{ji}\mathbf{u}_j and the mean of the latent variables includes the contributions u_{j,k(r)}\,x^{(r)}_{ji} of the random slopes. It is linear in \mathbf{u}_j, with coefficients that do not depend on \mathbf{u}_j, so that the outer expectation amounts to replacing \mathbf{u}_j by its posterior mean. The scores that are computed in this way are therefore the exact posterior means given all the data of the cluster. Their posterior variance, however, contains an additional term for the uncertainty about \mathbf{u}_j, which is not computed in version 0.7-4; this is why no standard errors are available at the within level.
Dempster, A. P., Laird, N. M., & Rubin, D. B. (1977). Maximum likelihood from incomplete data via the EM algorithm. Journal of the Royal Statistical Society: Series B (Methodological), 39(1), 1–38. https://doi.org/10.1111/j.2517-6161.1977.tb01600.x
Laird, N. M., & Ware, J. H. (1982). Random-effects models for longitudinal data. Biometrics, 38(4), 963–974.
Liang, J., & Bentler, P. M. (2004). An EM algorithm for fitting two-level structural equation models. Psychometrika, 69(1), 101–122.
Louis, T. A. (1982). Finding the observed information matrix when using the EM algorithm. Journal of the Royal Statistical Society: Series B (Methodological), 44(2), 226–233. https://doi.org/10.1111/j.2517-6161.1982.tb01203.x
McDonald, R. P., & Goldstein, H. (1989). Balanced versus unbalanced designs for linear structural relations in two-level data. British Journal of Mathematical and Statistical Psychology, 42(2), 215–232. https://doi.org/10.1111/j.2044-8317.1989.tb00911.x
Mehta, P. D., & Neale, M. C. (2005). People are variables too: Multilevel structural equations modeling. Psychological Methods, 10(3), 259–284. https://doi.org/10.1037/1082-989X.10.3.259
Muthén, B. O. (1990). Mean and covariance structure analysis of hierarchical data (UCLA Statistics Series 62). University of California, Los Angeles.
Rockwood, N. J. (2020). Maximum likelihood estimation of multilevel structural equation models with random slopes for latent covariates. Psychometrika, 85(2), 275–300. https://doi.org/10.1007/s11336-020-09702-9
Varadhan, R., & Roland, C. (2008). Simple and globally convergent methods for accelerating the convergence of any EM algorithm. Scandinavian Journal of Statistics, 35(2), 335–353. https://doi.org/10.1111/j.1467-9469.2007.00585.x