model <- '
visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9
'
fit <- cfa(model, data = HolzingerSwineford1939)13 Factor scores
13.1 From parameters to individual scores
The preceding chapters operated at the level of the model: estimating parameters (Section 7.2), attaching standard errors and test statistics to them (Section 8.4), and judging how well the model-implied summary statistics reproduce their sample counterparts (Section 10.1). The latent variables themselves have played only an indirect role: they enter the analysis only through the structure they impose on the means and covariances of the observed variables. In many applications, however, the user eventually wants a score for each latent variable and each individual case: to rank respondents on a latent trait, to plot the latent variables, to flag unusual observations, or to carry the latent variables into a follow-up analysis. These individual scores are called factor scores, and computing them is the topic of this chapter.
One point deserves emphasis from the outset: factor scores are predictions, not estimates. In the SEM framework, the latent variables \boldsymbol{\eta}_i are random variables, not fixed parameters; each case has its own realization, and this realization is never observed. What we can do is construct, for each case, a sensible predictor of \boldsymbol{\eta}_i from the observed data \mathbf{y}_i and the (estimated) model parameters (Skrondal & Rabe-Hesketh, 2004, Chapter 7). Because the observed variables contain measurement error, this prediction problem has no unique answer, and even the “true” scores are not uniquely determined by the model: this is the classical factor score indeterminacy problem (Section 13.2.5). Different predictors optimize different criteria, and the two classical choices, the regression method (Thomson, 1939; Thurstone, 1935) and the Bartlett method (Bartlett, 1937), both remain in use in modern software because each is optimal in its own sense.
In lavaan, factor scores (and several related casewise quantities) are computed by the lavPredict() function, briefly previewed in Section 9.10; the predict() method is a thin wrapper around it. Two companion tools extend the theme of casewise prediction: the Mahalanobis-distance diagnostics used by the outlier tools of Section 10.10, and lavPredictY(), which predicts observed outcome variables from other observed variables: prediction in the familiar regression sense, which lavPredict() deliberately does not do.
The chapter has four parts. We first derive the classical regression and Bartlett predictors in the notation of this book, and collect their properties (Section 13.2). We then discuss lavPredict() argument by argument, covering standard errors, transformed scores, multiple groups, missing data, categorical outcomes, and multilevel models (Section 13.3), and point out how the outlier diagnostics of chapter 10 build on it (Section 13.4). Next, we turn to lavPredictY() and its cross-validation companion (Section 13.5); the implementation notes at the end of the chapter (Section 13.7) describe the internal code paths. We close with a warning: using factor scores as if they were the latent variables themselves (for example, regressing one set of factor scores on another) produces biased estimates, and we explain why, pointing forward in Section 13.6 to the SAM approach of Chapter 18 for a principled solution. A classic review of factor scoring methods is Grice (2001).
The running example is once again the Holzinger–Swineford three-factor CFA:
13.2 The classical methods
13.2.1 A general linear predictor
Consider the measurement model for a single group with continuous observed variables,
\mathbf{y}_i = \boldsymbol{\nu}+ \boldsymbol{\Lambda}\,\boldsymbol{\eta}_i + \boldsymbol{\epsilon}_i, \qquad \text{Var}(\boldsymbol{\epsilon}_i) = \boldsymbol{\Theta}, \qquad \text{Cov}(\boldsymbol{\eta}_i, \boldsymbol{\epsilon}_i) = \mathbf{0}, \tag{13.1}
where \boldsymbol{\eta}_i is the M-dimensional vector of latent variables for case i. Writing \boldsymbol{\mu}_{\eta} = \mathrm{E}(\boldsymbol{\eta}) and \boldsymbol{\Psi}= \text{Var}(\boldsymbol{\eta}) for the (model-implied) latent moments, the observed variables have mean and variance
\boldsymbol{\mu}= \boldsymbol{\nu}+ \boldsymbol{\Lambda}\,\boldsymbol{\mu}_{\eta}, \qquad \boldsymbol{\Sigma}= \boldsymbol{\Lambda}\,\boldsymbol{\Psi}\,\boldsymbol{\Lambda}^{\prime}+ \boldsymbol{\Theta}, \qquad \text{Cov}(\mathbf{y}, \boldsymbol{\eta}) = \boldsymbol{\Lambda}\,\boldsymbol{\Psi}. \tag{13.2}
For a pure CFA model, \boldsymbol{\Psi} is a model matrix and \boldsymbol{\mu}_{\eta} = \boldsymbol{\alpha}. When the model contains a structural part, \boldsymbol{\Psi} and \boldsymbol{\mu}_{\eta} are understood as the model-implied latent moments obtained from the reduced form (Section 13.2.6); nothing else in this section changes.
All classical factor score methods are linear predictors of the form
\hat{\boldsymbol{\eta}}_i = \boldsymbol{\mu}_{\eta} + \mathbf{A}\,(\mathbf{y}_i - \boldsymbol{\mu}), \tag{13.3}
where \mathbf{A} is an M\times P factor score coefficient matrix (also called the factor score weight matrix). Any such predictor is marginally unbiased, \mathrm{E}(\hat{\boldsymbol{\eta}}) = \boldsymbol{\mu}_{\eta}, so the methods differ only in the choice of \mathbf{A}, and hence in the second-moment properties of the resulting scores. Two choices dominate the literature and are both available in lavaan. In practice, all population quantities in Equation 13.3 are replaced by their estimates: \mathbf{A} is built from (\hat{\boldsymbol{\Lambda}}, \hat{\boldsymbol{\Psi}}, \hat{\boldsymbol{\Theta}}), and \mathbf{y}_i is centered at the model-implied mean \hat{\boldsymbol{\mu}} (when there is no mean structure, the model-implied means default to the sample means, so the centering is at \bar{\mathbf{y}}).
13.2.2 The regression method
The regression method goes back to Thomson (1939) and Thurstone (1935). Under joint normality of (\mathbf{y}_i, \boldsymbol{\eta}_i), the conditional distribution of \boldsymbol{\eta}_i given \mathbf{y}_i is normal with mean
\mathrm{E}(\boldsymbol{\eta}_i \mid \mathbf{y}_i) = \boldsymbol{\mu}_{\eta} + \boldsymbol{\Psi}\,\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,(\mathbf{y}_i - \boldsymbol{\mu}), \tag{13.4}
which is Equation 13.3 with
\mathbf{A}_R = \boldsymbol{\Psi}\,\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}. \tag{13.5}
The regression predictor \hat{\boldsymbol{\eta}}_i^{\,R} = \boldsymbol{\mu}_{\eta} +
\mathbf{A}_R(\mathbf{y}_i - \boldsymbol{\mu}) is the posterior mean of \boldsymbol{\eta}_i, and it is therefore the empirical Bayes predictor; because the posterior is normal, the posterior mean and the posterior mode coincide, which is why the lavaan option method = "EBM" (empirical Bayes modal) is an alias for the regression method in the continuous case. Among all predictors (linear or not), the posterior mean minimizes the mean squared prediction error \mathrm{E}\{(\hat{\boldsymbol{\eta}} - \boldsymbol{\eta})^{\prime}(\hat{\boldsymbol{\eta}} - \boldsymbol{\eta})\}; among linear predictors it does so even without the normality assumption (it is the best linear predictor).
Three properties of the regression scores are worth mentioning. First, their variance matrix is smaller than \boldsymbol{\Psi}:
\text{Var}(\hat{\boldsymbol{\eta}}^{\,R}) = \mathbf{A}_R\,\boldsymbol{\Sigma}\,\mathbf{A}_R^{\prime} = \boldsymbol{\Psi}\,\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,\boldsymbol{\Lambda}\,\boldsymbol{\Psi} \;\preceq\; \boldsymbol{\Psi}. \tag{13.6}
The scores are shrunken towards the latent mean, exactly as empirical Bayes predictors in mixed models are shrunken towards zero. Second, they are conditionally biased: given the true latent value \boldsymbol{\eta}_i,
\mathrm{E}(\hat{\boldsymbol{\eta}}_i^{\,R} \mid \boldsymbol{\eta}_i) = \boldsymbol{\mu}_{\eta} + \mathbf{C}\,(\boldsymbol{\eta}_i - \boldsymbol{\mu}_{\eta}), \qquad \mathbf{C} = \boldsymbol{\Psi}\,\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,\boldsymbol{\Lambda}, \tag{13.7}
where the shrinkage matrix \mathbf{C} is not the identity: cases with extreme latent values receive systematically less extreme scores. Third, the covariance between the scores and the latent variables equals the variance of the scores,
\text{Cov}(\hat{\boldsymbol{\eta}}^{\,R}, \boldsymbol{\eta}) = \mathbf{A}_R\,\text{Cov}(\mathbf{y}, \boldsymbol{\eta}) = \boldsymbol{\Psi}\,\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,\boldsymbol{\Lambda}\,\boldsymbol{\Psi} = \text{Var}(\hat{\boldsymbol{\eta}}^{\,R}), \tag{13.8}
a property that will play a central role when factor scores are used as predictors in a follow-up regression (Section 13.6). Finally, the conditional (posterior) variance
\text{Var}(\boldsymbol{\eta}_i - \hat{\boldsymbol{\eta}}_i^{\,R} \mid \mathbf{y}_i) = \boldsymbol{\Psi} - \boldsymbol{\Psi}\,\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,\boldsymbol{\Lambda}\,\boldsymbol{\Psi} \tag{13.9}
quantifies the prediction uncertainty; it does not depend on \mathbf{y}_i, so it is the same for every (complete) case. This is the matrix lavaan reports when standard errors are requested for regression scores (Section 13.3.5).
13.2.3 The Bartlett method
The Bartlett method (Bartlett, 1937; see also Lawley & Maxwell, 1971) takes the opposite perspective: it treats \boldsymbol{\eta}_i as a fixed unknown for case i, and asks which value of \boldsymbol{\eta}_i makes the observed \mathbf{y}_i most likely. Given \boldsymbol{\eta}_i (and the model parameters), the measurement model of Equation 13.1 with normal residuals says that \mathbf{y}_i is normal with mean \boldsymbol{\nu}+ \boldsymbol{\Lambda}\,\boldsymbol{\eta}_i and variance \boldsymbol{\Theta}, so that the log-likelihood of \mathbf{y}_i, viewed as a function of \boldsymbol{\eta}_i, is
\ell(\boldsymbol{\eta}_i) = \text{const} - \tfrac{1}{2}\, (\mathbf{y}_i - \boldsymbol{\nu}- \boldsymbol{\Lambda}\,\boldsymbol{\eta}_i)^{\prime}\, \boldsymbol{\Theta}^{-1}\, (\mathbf{y}_i - \boldsymbol{\nu}- \boldsymbol{\Lambda}\,\boldsymbol{\eta}_i). \tag{13.10}
This is how Bartlett framed the problem, and it is the origin of the name maximum likelihood (ML) factor scores, and of the lavaan alias method = "ML". Setting the derivative of Equation 13.10 with respect to \boldsymbol{\eta}_i to zero gives the normal equations \boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}(\mathbf{y}_i - \boldsymbol{\nu}) =
(\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\,\boldsymbol{\Lambda})\,\boldsymbol{\eta}_i. The same equations arise from a more familiar angle: maximizing Equation 13.10 is the same as minimizing the quadratic form in its second term, which is the weighted least squares problem of regressing \mathbf{y}_i - \boldsymbol{\nu} on the known design matrix \boldsymbol{\Lambda} with weight matrix \boldsymbol{\Theta}^{-1}, and the solution is immediate: Equation 13.3 with
\mathbf{A}_B = (\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\,\boldsymbol{\Lambda})^{-1}\, \boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}. \tag{13.11}
(Centering at \boldsymbol{\mu} or at \boldsymbol{\nu} makes no difference here, because \mathbf{A}_B\boldsymbol{\Lambda}= \mathbf{I}.) The defining property of the Bartlett predictor is conditional unbiasedness:
\mathrm{E}(\hat{\boldsymbol{\eta}}_i^{\,B} \mid \boldsymbol{\eta}_i) = \boldsymbol{\eta}_i, \tag{13.12}
which follows immediately from \mathbf{A}_B\boldsymbol{\Lambda}= \mathbf{I}. By the Gauss–Markov logic, \hat{\boldsymbol{\eta}}^{\,B} has the smallest conditional variance among all linear predictors that are conditionally unbiased. The price of unbiasedness is excess variance: the Bartlett scores are more variable than the latent variables themselves,
\text{Var}(\hat{\boldsymbol{\eta}}^{\,B}) = \boldsymbol{\Psi}+ (\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\,\boldsymbol{\Lambda})^{-1} \;\succeq\; \boldsymbol{\Psi}, \qquad \text{Var}(\hat{\boldsymbol{\eta}}_i^{\,B} - \boldsymbol{\eta}_i \mid \boldsymbol{\eta}_i) = (\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\,\boldsymbol{\Lambda})^{-1}. \tag{13.13}
The first expression is the asymptotic variance matrix used for the leverage Mahalanobis distances in Section 10.10.2.
lavaan does not implement Equation 13.11 literally. Using the Woodbury identity (appendix B.7), one can show that
\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1} = \left(\mathbf{I} + \boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\,\boldsymbol{\Lambda}\,\boldsymbol{\Psi}\right)^{-1} \boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1},
so that pre-multiplying by (\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1}\boldsymbol{\Lambda})^{-1} gives the equivalent “GLS” form
\mathbf{A}_B = (\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,\boldsymbol{\Lambda})^{-1}\, \boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}, \tag{13.14}
which is what the code computes (following Bentler & Yuan, 1997). The \boldsymbol{\Sigma}-based form has an important practical advantage: it remains well-defined when \boldsymbol{\Theta} is singular (for example, when a single-indicator construct has a residual variance fixed at zero), as long as \boldsymbol{\Sigma} itself is invertible. A companion identity,
(\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,\boldsymbol{\Lambda})^{-1} = \boldsymbol{\Psi} + (\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Theta}^{-1}\,\boldsymbol{\Lambda})^{-1}, \tag{13.15}
shows that the conditional variance in Equation 13.13 equals (\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1}\boldsymbol{\Lambda})^{-1} - \boldsymbol{\Psi}, so that \boldsymbol{\Theta}^{-1} can be avoided for the standard errors as well (Section 13.3.5 computes them from a general expression that reduces to this form). For the rare settings where even \boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1}\boldsymbol{\Lambda} is singular by construction, lavaan falls back to a Moore–Penrose pseudo-inverse; the resulting scores are then no longer conditionally unbiased.
13.2.4 Comparing the two methods
The two coefficient matrices are directly related. Combining Equation 13.5 and Equation 13.14,
\mathbf{A}_R = \boldsymbol{\Psi}\,\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,\boldsymbol{\Lambda}\;\mathbf{A}_B = \mathbf{C}\,\mathbf{A}_B, \tag{13.16}
so the regression scores are, case by case, a matrix-shrunken version of the Bartlett scores, with the same shrinkage matrix \mathbf{C} that appears in Equation 13.7. A less obvious consequence is that the cross-covariance between the two sets of scores reproduces the latent variance matrix exactly:
\text{Cov}(\hat{\boldsymbol{\eta}}^{\,R}, \hat{\boldsymbol{\eta}}^{\,B}) = \mathbf{A}_R\,\boldsymbol{\Sigma}\,\mathbf{A}_B^{\prime} = \boldsymbol{\Psi}\,\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,\boldsymbol{\Lambda}\, (\boldsymbol{\Lambda}^{\prime}\,\boldsymbol{\Sigma}^{-1}\,\boldsymbol{\Lambda})^{-1} = \boldsymbol{\Psi}, \tag{13.17}
while neither method reproduces \boldsymbol{\Psi} on its own (Equation 13.6 and Equation 13.13). Table 13.1 summarizes the contrast.
| Property | Regression ("regression", "EBM") |
Bartlett ("Bartlett", "ML") |
|---|---|---|
| Coefficient matrix \mathbf{A} | \boldsymbol{\Psi}\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1} | (\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1}\boldsymbol{\Lambda})^{-1}\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1} |
| Optimality | minimal MSE (posterior mean) | minimal variance among conditionally unbiased |
| \mathrm{E}(\hat{\boldsymbol{\eta}}_i \mid \boldsymbol{\eta}_i) | \boldsymbol{\mu}_{\eta} + \mathbf{C}(\boldsymbol{\eta}_i - \boldsymbol{\mu}_{\eta}) (shrunken) | \boldsymbol{\eta}_i (conditionally unbiased) |
| \text{Var}(\hat{\boldsymbol{\eta}}) | \boldsymbol{\Psi}\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1}\boldsymbol{\Lambda}\boldsymbol{\Psi}\preceq \boldsymbol{\Psi} | \boldsymbol{\Psi}+ (\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Theta}^{-1}\boldsymbol{\Lambda})^{-1} \succeq \boldsymbol{\Psi} |
| Prediction variance | \boldsymbol{\Psi}- \boldsymbol{\Psi}\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1}\boldsymbol{\Lambda}\boldsymbol{\Psi} | (\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Theta}^{-1}\boldsymbol{\Lambda})^{-1} |
| Casewise residual \mathbf{y}_i - \hat{\mathbf{y}}_i | contaminated by \hat{\boldsymbol{\eta}}_i | orthogonal to \mathrm{col}(\boldsymbol{\Lambda}) in the \boldsymbol{\Theta}^{-1} metric |
The last row of the table (the orthogonality of the Bartlett-based casewise residuals, which makes them interpretable as uncontaminated estimates of the measurement errors) was discussed in Section 10.10.1 and is the reason the outlier diagnostics of Section 10.10 use Bartlett (not regression) scores.
A small numerical check makes these properties concrete. For the running example, the empirical variance matrix of the regression scores is noticeably smaller than \hat{\boldsymbol{\Psi}}, that of the Bartlett scores noticeably larger, and the cross-covariance lies in between:
fs_r <- lavPredict(fit, method = "regression")
fs_b <- lavPredict(fit, method = "Bartlett")
PSI <- lavInspect(fit, "est")$psi
round(diag(PSI), 3) # model-implied latent variances visual textual speed
0.809 0.979 0.384
round(diag(cov(fs_r)), 3) # regression scores: shrunken visual textual speed
0.586 0.872 0.277
round(diag(cov(fs_b)), 3) # Bartlett scores: inflated visual textual speed
1.181 1.110 0.548
round(diag(cov(fs_r, fs_b)), 3) # cross-covariance: close to Psi visual textual speed
0.812 0.983 0.385
(The empirical values match the population expressions only approximately, because the sample covariance matrix \mathbf{S} is not exactly equal to the fitted \hat{\boldsymbol{\Sigma}} from which the weights are built.) The two sets of scores are strongly but not perfectly correlated; Figure 13.1 shows the shrinkage at the level of the individual cases.
fs_visual <- data.frame(bartlett = fs_b[, "visual"],
regression = fs_r[, "visual"])
tinyplot(regression ~ bartlett, data = fs_visual,
xlab = "Bartlett score (visual)",
ylab = "Regression score (visual)")
tinyplot_add(type = "abline", lty = 2)
13.2.5 Factor score indeterminacy
Even with the model parameters known exactly, the latent variables are not uniquely determined by the observed data: infinitely many random vectors \boldsymbol{\eta}^{*} are consistent with the same \boldsymbol{\Lambda}, \boldsymbol{\Psi}, \boldsymbol{\Theta}, and the same joint distribution of the observed variables (Guttman, 1955). This is factor score indeterminacy, and it implies that no scoring method can “recover” the factors; it is only possible to quantify how strongly any constructed score correlates with its target factor.
The standard summary is the factor determinacy coefficient (also called the validity coefficient of the factor scores): the correlation between the score and the factor it predicts. For an arbitrary coefficient matrix \mathbf{A},
\rho_m = \text{Cor}(\hat{\eta}_m, \eta_m) = \frac{[\mathbf{A}\,\boldsymbol{\Lambda}\,\boldsymbol{\Psi}]_{mm}} {\sqrt{[\mathbf{A}\,\boldsymbol{\Sigma}\,\mathbf{A}^{\prime}]_{mm}\; [\boldsymbol{\Psi}]_{mm}}}, \qquad m = 1, \ldots, M. \tag{13.18}
For the regression method, Equation 13.8 reduces this to \rho_m = \sqrt{[\boldsymbol{\Psi}\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1}\boldsymbol{\Lambda} \boldsymbol{\Psi}]_{mm} / [\boldsymbol{\Psi}]_{mm}}, and no linear method can do better: the regression score is, by construction, the linear combination of the observed variables that is maximally correlated with the factor. The squared determinacy \rho^2_m is the reliability of the factor score (the proportion of its variance that is “valid” variance). Guttman’s classic argument shows that two equally admissible versions of the factor can correlate as low as 2\rho^2_m - 1; determinacies below \sqrt{0.5} \approx 0.71 therefore signal that the “factor” is poorly determined by its indicators. See Grice (2001) for a review and practical guidelines.
In lavaan, the reliabilities \rho^2_m are returned by adding rel = TRUE:
fs <- lavPredict(fit, method = "regression", rel = TRUE)
attr(fs, "rel")[[1]]
visual textual speed
0.7215243 0.8877133 0.7202203
The values are computed from Equation 13.18 with the estimated moments, and therefore adapt automatically to the method: for Bartlett scores the reliabilities are somewhat lower, since the added measurement-error variance in Equation 13.13 dilutes the correlation:
fs <- lavPredict(fit, method = "Bartlett", rel = TRUE)
attr(fs, "rel")[[1]]
visual textual speed
0.6877556 0.8852806 0.7031279
13.2.6 Beyond the pure CFA model
Nothing in Section 13.2.1 requires the model to be a pure CFA. When the model contains a structural part
\boldsymbol{\eta}_i = \boldsymbol{\alpha}+ \mathbf{B}\,\boldsymbol{\eta}_i + \boldsymbol{\zeta}_i,
the latent moments in Equation 13.3 are replaced by their model-implied (reduced-form) counterparts,
\boldsymbol{\mu}_{\eta} = (\mathbf{I} - \mathbf{B})^{-1}\,\boldsymbol{\alpha}, \qquad \boldsymbol{\Psi}^{*} \equiv \text{Var}(\boldsymbol{\eta}) = (\mathbf{I} - \mathbf{B})^{-1}\,\boldsymbol{\Psi}\,(\mathbf{I} - \mathbf{B}^{\prime})^{-1}, \tag{13.19}
and \boldsymbol{\Sigma}= \boldsymbol{\Lambda}\boldsymbol{\Psi}^{*}\boldsymbol{\Lambda}^{\prime}+ \boldsymbol{\Theta} is the full model-implied variance matrix. For the regression method, the scores of each latent variable borrow strength from the indicators of all the others (the weights run through the full \boldsymbol{\Sigma}^{-1}), and in a structural model the strength of that borrowing is governed by the reduced-form \boldsymbol{\Psi}^{*}, that is, by the structural coefficients. Bartlett scores, by contrast, use only a factor’s own indicators when \boldsymbol{\Theta} is diagonal. We can verify the regression weights for the political democracy model, whose latent variance matrix involves the structural coefficients:
modelPD <- '
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem65 =~ y5 + y6 + y7 + y8
dem60 ~ ind60
dem65 ~ ind60 + dem60
'
fitPD <- sem(modelPD, data = PoliticalDemocracy)
fsPD <- lavPredict(fitPD, fsm = TRUE) # regression scores + weights
# rebuild the coefficient matrix by hand from the reduced form
EST <- lavInspect(fitPD, "est")
IBinv <- solve(diag(nrow(EST$beta)) - EST$beta)
VETA <- IBinv %*% EST$psi %*% t(IBinv)
SIGMA <- EST$lambda %*% VETA %*% t(EST$lambda) + EST$theta
A_R <- VETA %*% t(EST$lambda) %*% solve(SIGMA)
all.equal(attr(fsPD, "fsm")[[1]], A_R, check.attributes = FALSE)[1] TRUE
Two further complications are handled transparently. First, observed variables that appear in the structural part are represented internally by dummy latent variables (Section 4.3.4); their “factor scores” are the observed values themselves, and lavaan substitutes those before returning the result (the dummy columns themselves are removed from the output). Second, when exogenous observed covariates are involved, the scores condition on each case’s covariate values: explicitly under conditional_x = TRUE, through per-case latent means \mathrm{E}(\boldsymbol{\eta}_i \mid \mathbf{x}_i) and the conditional latent variance \text{Var}(\boldsymbol{\eta}\mid \mathbf{x}) = (\mathbf{I} - \mathbf{B})^{-1}\boldsymbol{\Psi}(\mathbf{I} - \mathbf{B}^{\prime})^{-1}, and implicitly under fixed_x = TRUE alone, because the covariates are then part of the vector \mathbf{y}_i that enters \mathbf{A}(\mathbf{y}_i -
\boldsymbol{\mu}). Both routes give the same scores.
13.3 lavPredict() in practice
13.3.1 The function and its defaults
A typical call to lavPredict() names the fitted object and, at most, a few arguments; the call below lists the defaults of the five arguments that the following subsections discuss:
fs <- lavPredict(fit, type = "lv", method = "EBM",
se = "none", acov = "none", transform = FALSE)The type argument selects what is predicted (factor scores, fitted indicator values, residuals), method the scoring method ("EBM" is an alias for the regression method, Section 13.2.2), se and acov whether standard errors and the prediction variance matrix are returned, and transform whether the correlation-preserving transformation is applied. The remaining arguments (among them newdata, fsm, mdist, level, append_data, and the parallel-processing settings) are introduced where they are needed; ?lavPredict lists them all. The generic predict() method for lavaan objects calls lavPredict(object, newdata = newdata, type = "lv", method = "EBM"), so
all.equal(predict(fit), lavPredict(fit))[1] TRUE
For a single group, the result is an N\times M matrix of class lavaan.matrix, with one column per latent variable (labeled, unless label = FALSE). For efaList objects (the output of efa()), both functions extract the last (largest) solution and score that.
13.3.2 The type argument
The type argument selects what is predicted for each case (Table 13.2); the aliases are normalized before any other processing.
type argument of lavPredict().
type= |
Aliases | Returns (per case) |
|---|---|---|
"lv" (default) |
"latent", "factor", "factor_score", "factorscore" |
factor scores \hat{\boldsymbol{\eta}}_i |
"yhat" |
"ov" |
fitted indicator values \hat{\mathbf{y}}_i = \hat{\boldsymbol{\nu}} + \hat{\boldsymbol{\Lambda}}\hat{\boldsymbol{\eta}}_i\;(+\,\hat{\mathbf{K}}\mathbf{x}_i) |
"resid" |
"residuals", "error" |
casewise residuals \mathbf{y}_i - \hat{\mathbf{y}}_i |
"fy" |
(none) | casewise densities f(y_p\mid \hat{\boldsymbol{\eta}}_i), per indicator |
For type = "yhat", the factor scores are computed first (with the requested method), and then substituted into the measurement equation. Alternatively, the user can supply latent variable values directly through the eta argument (a single vector of length M, recycled for all cases, or a full N\times M matrix), in which case no scoring takes place at all. The residual type is the difference:
yhat <- lavPredict(fit, type = "yhat")
res <- lavPredict(fit, type = "residuals")
Y <- lavInspect(fit, "data")
all.equal(unclass(res), unclass(Y - yhat), check.attributes = FALSE)[1] TRUE
Casewise residuals are not available for categorical endogenous variables (there is no natural residual on the observed scale), unless mdist = TRUE, in which case the expected residuals of the underlying latent responses are returned (see Section 13.4). Finally, type = "fy" returns, for each case and each indicator, the conditional density (for continuous indicators) or conditional category probability (for ordered indicators) given the case’s factor scores. This casewise quantity is mainly used internally by the marginal maximum likelihood (MML) estimator, but it can occasionally be useful for person-fit inspection.
13.3.3 The method argument
The method argument selects the factor score coefficient matrix. The value is not case-sensitive, and there are two families of aliases:
method = "regression"ormethod = "EBM"(the current default): the regression / empirical-Bayes predictor of Section 13.2.2;method = "Bartlett"(the misspelling"bartlet"is also accepted) ormethod = "ML": the Bartlett predictor of Section 13.2.3.
The pairs of names reflect the two settings in which the methods arise. For continuous indicators the computation is the closed-form linear map of Equation 13.3, and the names “regression” and “Bartlett” are natural. For categorical indicators (Section 13.3.9) there is no closed form: "EBM" then maximizes the posterior density (empirical Bayes modal), and "ML" maximizes the case’s likelihood. These are the natural generalizations of the regression and Bartlett predictors, respectively.
head(lavPredict(fit, method = "Bartlett"), 3) visual textual speed
[1,] -1.36953833 -0.09954953 0.2318368
[2,] 0.07592894 -1.19815080 0.9886425
[3,] -0.56109959 -2.10473912 -1.1216774
13.3.4 The factor score matrix: fsm = TRUE
Setting fsm = TRUE attaches the estimated coefficient matrix \hat{\mathbf{A}} itself (one per group) as the "fsm" attribute of the result, with latent variables in the rows and observed indicators in the columns:
fs <- lavPredict(fit, method = "regression", fsm = TRUE)
round(attr(fs, "fsm")[[1]], 3) x1 x2 x3 x4 x5 x6 x7 x8 x9
visual 0.410 0.110 0.195 0.041 0.038 0.039 0.030 0.058 0.046
textual 0.028 0.007 0.013 0.296 0.274 0.286 0.005 0.009 0.007
speed 0.044 0.012 0.021 0.010 0.009 0.010 0.134 0.260 0.205
The weight matrix is useful for understanding which indicators contribute most to each score. Note, in this example, the small but nonzero weights that the indicators of the other factors receive, a consequence of the correlated factors entering through \boldsymbol{\Sigma}^{-1}. The weight matrix is also an essential ingredient of the SAM approach (Section 18.3), where the mapping matrix is used to correct the moments of the factor scores rather than the scores themselves.
13.3.5 Standard errors: se= and acov=
With se = "standard", lavaan returns standard errors for the factor scores as the "se" attribute; with acov = "standard" (which implies se), the full prediction variance matrix is attached as "acov". For continuous data, every score that lavPredict() returns is a linear function of the data, \hat{\boldsymbol{\eta}}_i = \boldsymbol{\mu}_{\eta} +
\mathbf{A}(\mathbf{y}_i - \boldsymbol{\mu}) as in Equation 13.3, where \mathbf{A} is the coefficient matrix of the scores that are actually returned (the "fsm" attribute). The prediction error is therefore \hat{\boldsymbol{\eta}}_i - \boldsymbol{\eta}_i = \mathbf{A}(\mathbf{y}_i - \boldsymbol{\mu}) - (\boldsymbol{\eta}_i -
\boldsymbol{\mu}_{\eta}), and its variance follows from the moments of Equation 13.2, with \text{Var}(\mathbf{y}) = \boldsymbol{\Sigma}, \text{Cov}(\mathbf{y}, \boldsymbol{\eta}) = \boldsymbol{\Lambda}\boldsymbol{\Psi}, and \text{Var}(\boldsymbol{\eta}) = \boldsymbol{\Psi}:
\text{Var}(\hat{\boldsymbol{\eta}}_i - \boldsymbol{\eta}_i) = \mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^{\prime} - \mathbf{A}\boldsymbol{\Lambda}\boldsymbol{\Psi} - \boldsymbol{\Psi}\boldsymbol{\Lambda}^{\prime}\mathbf{A}^{\prime} + \boldsymbol{\Psi}. \tag{13.20}
The standard errors are the square roots of the diagonal of Equation 13.20 evaluated at the estimates, and "acov" is the whole matrix. The expression holds for any linear scoring rule, which is what makes it the single route lavaan uses: for the classical methods, for the transformed scores of Section 13.3.6 (where \mathbf{A} includes the transformation), for the pattern-specific scores under missing data, for two-level models, and for the higher-order rows of Section 13.3.11. For the two classical methods, it reduces to the familiar forms. Substituting the regression weights \mathbf{A}_R = \boldsymbol{\Psi}\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1} makes the first two terms cancel, and for the Bartlett weights \mathbf{A}_B\boldsymbol{\Lambda}= \mathbf{I} collapses the two middle terms to -\boldsymbol{\Psi}, so that
\text{Var}(\hat{\boldsymbol{\eta}}_i - \boldsymbol{\eta}_i) = \begin{cases} \boldsymbol{\Psi}- \boldsymbol{\Psi}\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1}\boldsymbol{\Lambda}\boldsymbol{\Psi} & \text{(regression),}\\[0.5em] \mathbf{A}_B\boldsymbol{\Sigma}\mathbf{A}_B^{\prime} - \boldsymbol{\Psi} \;=\; (\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1}\boldsymbol{\Lambda})^{-1} - \boldsymbol{\Psi} \;=\; (\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Theta}^{-1}\boldsymbol{\Lambda})^{-1} & \text{(Bartlett),} \end{cases} \tag{13.21}
that is, Equation 13.9 and Equation 13.13. For complete data the matrix is the same for every case, so the "se" attribute contains a single row per group; diagonal elements smaller than 10^{-5} are returned as NA.
fs <- lavPredict(fit, method = "Bartlett", se = "standard",
acov = "standard")
attr(fs, "se")[[1]]
visual textual speed
[1,] 0.6061629 0.3562693 0.4025227
round(attr(fs, "acov")[[1]], 3) visual textual speed
visual 0.367 0.000 0.000
textual 0.000 0.127 0.000
speed 0.000 0.000 0.162
The standard errors of Equation 13.20 are naive in one respect: they treat the model parameters as known, and therefore quantify only the irreducible prediction error given the fitted model, not the additional sampling variability that comes from estimating \hat{\boldsymbol{\vartheta}} from the same N cases. For large samples the neglected component is of smaller order (the prediction error is O(1) while the parameter uncertainty is O(1/N)), but in small samples the reported standard errors can be noticeably too small. The same caveat applies to the categorical case below, where the Laplace-based standard errors are again conditional on \hat{\boldsymbol{\vartheta}}.
Standard errors are only available for type = "lv"; requesting them for type = "yhat" or type = "resid" results in an error. For missing data the standard errors become pattern-specific, and for categorical data case-specific; both settings are discussed below.
13.3.6 Correlation-preserving scores: transform = TRUE
As Equation 13.6 and Equation 13.13 make explicit, neither classical method produces scores whose variance matrix equals \boldsymbol{\Psi}: regression scores are too concentrated, Bartlett scores too dispersed, and in both cases the correlations among the scores are distorted as well. When the scores are used in a descriptive follow-up analysis, it may be desirable that they reproduce the model-implied latent variance matrix exactly. Correlation-preserving scoring methods achieve this by applying a carefully chosen linear transformation \mathbf{A} \rightarrow \mathbf{T}\mathbf{A} such that \mathbf{T}\mathbf{A}\,\boldsymbol{\Sigma}\,\mathbf{A}^{\prime}\mathbf{T}^{\prime} = \boldsymbol{\Psi}, while keeping the transformed scores as close as possible to their untransformed parents (Berge et al., 1999).
Setting transform = TRUE in lavPredict() selects this option. For the regression method, the transformation matrix is the one due to Green (1969); for the Bartlett method, it is the determinacy-based transformation associated with McDonald (1981) and Krijnen (see Berge et al., 1999). Both transformations operate on the coefficient matrix before the scores are computed, so fsm = TRUE returns the transformed weights, and the guarantee holds at the level of the model-implied moments:
fs_t <- lavPredict(fit, method = "regression", transform = TRUE,
fsm = TRUE)
C_t <- attr(fs_t, "fsm")[[1]]
SIGMA <- lavInspect(fit, "cov_ov")
round(C_t %*% SIGMA %*% t(C_t), 3) # equals the model-implied Psi visual textual speed
visual 0.809 0.408 0.262
textual 0.408 0.979 0.173
speed 0.262 0.173 0.384
round(unclass(PSI), 3) visual textual speed
visual 0.809 0.408 0.262
textual 0.408 0.979 0.173
speed 0.262 0.173 0.384
(The empirical variance matrix of the transformed scores matches \hat{\boldsymbol{\Psi}} up to the divisor N- 1 of cov() and, when \boldsymbol{\Psi} is not saturated or the estimator is not ML, up to the difference between \mathbf{S} and \hat{\boldsymbol{\Sigma}}.) The transformed scores remain very highly correlated with their untransformed counterparts. Standard errors and the "acov" attribute are available for transformed scores as for any other: because the transformation acts on the coefficient matrix, Equation 13.20 applies with \mathbf{T}\mathbf{A} in place of \mathbf{A}, and the standard errors are the root mean squared prediction errors of the transformed scores (not the posterior standard deviations of the regression scores they were derived from). For categorical data, where the scores are not linear in the data, the sampling variance matrix of the transformed scores is the delta-method form \mathbf{T}\,\widehat{\mathrm{ACOV}}\,\mathbf{T}^{\prime}.
fs_r_se <- lavPredict(fit, method = "regression", se = "standard")
fs_t_se <- lavPredict(fit, method = "regression", transform = TRUE,
se = "standard")
rbind(regression = attr(fs_r_se, "se")[[1]][1, ],
transformed = attr(fs_t_se, "se")[[1]][1, ]) visual textual speed
regression 0.4747366 0.3316382 0.3276657
transformed 0.4977878 0.3393535 0.3452563
The transformation is not restricted to complete, continuous, unconditional data; four extensions are worth noting. Under missing = "ml", the transformation matrix is computed separately for each missing-data pattern, so that both the per-pattern and the pooled scores reproduce the model-implied \boldsymbol{\Psi}; if for some pattern all indicators of a factor are missing, that pattern’s transformation falls back to a pseudo-inverse and only partially restores the (co)variances involving that factor (lavaan warns when this happens, and the Bartlett NA rule of Section 13.3.8 is preserved). Under conditional_x = TRUE, the transformation restores the conditional variance of the factors given the covariates, so that the marginal variance of the transformed scores again matches the unconditional \boldsymbol{\Psi}. For factors without observed indicators (higher-order factors, phantom factors), the guarantee cannot hold in full: both their regression scores and their Bartlett scores are an exact linear function of the scores of the factors with indicators, so no linear transformation can give them the model-implied variance. The transformation is then applied to the factors with observed indicators only, and the scores of the other factors are the model-implied conditional means given these (transformed) scores: their covariances with the other factors are restored, their variance is the explained part only, and a warning names them. Finally, for categorical data, where the scores are a nonlinear function of the response pattern and no closed-form score variance exists, the transformation is based on the empirical variance matrix of the factor scores, and the sample variance of the transformed scores then matches \hat{\boldsymbol{\Psi}} exactly (see Section 13.3.9).
13.3.7 Multiple groups, newdata, and output layout
For a multigroup model, lavPredict() computes the weights per group (each group has its own model matrices, and hence its own \hat{\mathbf{A}}_g) and returns a list of score matrices, one per group, named by the group labels:
fitg <- cfa(model, data = HolzingerSwineford1939, group = "school")
fsg <- lavPredict(fitg)
lapply(fsg, head, 2)$Pasteur
visual textual speed
[1,] -1.2015845 0.08160746 0.005824318
[2,] 0.1242508 -0.72176498 0.461187784
$`Grant-White`
visual textual speed
[1,] -1.05764087 -0.4995383 -0.8719154
[2,] -0.09177192 -0.6196382 -0.3481611
Three arguments control the output layout:
assemble = TRUEreassembles the per-group matrices into a single data frame with the same row order as the original data, adding the group variable as a final column. This is the convenient format for merging the scores back into the dataset.append_data = TRUE(only fortype = "lv"; ignored, with a warning, whenlevel = 2) binds the observed data columns to the right of the factor scores.drop_list_single_group = FALSEkeeps the list structure even for a single group, which is convenient in programmatic use.
head(lavPredict(fitg, assemble = TRUE), 3) visual textual speed school
1 -1.2015845 0.08160746 0.005824318 Pasteur
2 0.1242508 -0.72176498 0.461187784 Pasteur
3 -0.6579449 -1.60994497 -0.905093125 Pasteur
The newdata argument scores new cases with the parameter estimates of the fitted model: the data frame is processed in the same way as the original data (a fresh internal lavData object is built, with the same options), and the resulting observations are passed through Equation 13.3. Incomplete rows of newdata follow the missing setting of the fit: under missing = "listwise" (the default) they are silently dropped, under missing = "ml" they are scored per missing-data pattern (Section 13.3.8). For a multigroup fit, newdata must contain the group variable, with every group present. For ordered indicators, the number of observed categories in newdata must match the original data. For multilevel models, newdata must contain the cluster variable, and the cluster structure (and, under missing = "ml", the missingness patterns) are rebuilt from the new data, so that entirely new clusters can be scored.
13.3.8 Missing data
When the model was fitted with missing = "ml" (or "ml.x"), factor scores are computed per missing-data pattern. For a case in pattern p with observed subvector \mathbf{y}_{i,\mathrm{obs}}, the weights of Equation 13.3 are rebuilt from the corresponding submatrices: the rows of \hat{\boldsymbol{\Lambda}} for the observed variables, and the inverse of the corresponding block of \hat{\boldsymbol{\Sigma}} (obtained efficiently from the full \hat{\boldsymbol{\Sigma}}^{-1} by an inverse-update formula, rather than by a fresh inversion per pattern). For the regression method, this yields exactly \mathrm{E}(\boldsymbol{\eta}_i \mid \mathbf{y}_{i,\mathrm{obs}}), the empirical Bayes predictor given the variables that were observed. The prediction variance (Equation 13.21) now differs across patterns, so the "se" attribute becomes a full N\times M matrix, and acov = "standard" returns one variance matrix per pattern:
HSmiss <- HolzingerSwineford1939
set.seed(1)
HSmiss[sample(301, 60), "x1"] <- NA
HSmiss[sample(301, 60), "x5"] <- NA
fitm <- cfa(model, data = HSmiss, missing = "ml")
fsm <- lavPredict(fitm, se = "standard")
head(attr(fsm, "se")[[1]], 4) # SEs vary with the pattern visual textual speed
[1,] 0.4584324 0.3979359 0.3242591
[2,] 0.4576900 0.3329122 0.3241577
[3,] 0.4576900 0.3329122 0.3241577
[4,] 0.4576900 0.3329122 0.3241577
One Bartlett-specific subtlety: if all indicators of a factor are missing for some pattern, the corresponding column of the pattern-specific \hat{\boldsymbol{\Lambda}} is zero, and the (pseudo-inverse based) Bartlett map would silently return a score of exactly zero. lavaan replaces such scores by NA: for a conditionally unbiased method there is no information about that factor in the observed variables. The regression method, by contrast, still returns a value in this situation: the empirical Bayes prediction then borrows entirely from the correlated factors (and shrinks heavily towards the mean), which is meaningful for a posterior-mean predictor but has no analogue in the Bartlett framework. With missing = "listwise" (the default), only the complete cases are scored, and the complete-data formulas apply unchanged. The correlation-preserving transformation of Section 13.3.6 carries over to this setting as well: with missing = "ml", the transformation matrix is rebuilt per missing-data pattern, so the transformed scores reproduce the model-implied latent variance matrix both within each pattern and overall.
13.3.9 Categorical data: EBM and ML
When (some of) the indicators are ordered categorical, the linear map of Equation 13.3 no longer applies: the relation between \boldsymbol{\eta}_i and the observed responses runs through the thresholds of the latent responses \mathbf{y}^{\star} (Section 14.2.1 in chapter 14). lavaan then computes the factor scores by numerical optimization, case by case. Write f(y_p\mid \boldsymbol{\eta}_i) for the conditional probability of the observed response on indicator p. For an ordered indicator with observed category c,
f(y_p= c \mid \boldsymbol{\eta}_i) = \Phi\!\left(\frac{\tau^{(c)}_p - \hat{y}^{\star}_{p}(\boldsymbol{\eta}_i)} {\sqrt{\theta_{pp}}}\right) - \Phi\!\left(\frac{\tau^{(c-1)}_p - \hat{y}^{\star}_{p}(\boldsymbol{\eta}_i)} {\sqrt{\theta_{pp}}}\right), \tag{13.22}
with \hat{y}^{\star}_{p}(\boldsymbol{\eta}_i) the linear predictor of the latent response and \Phi the standard-normal distribution function (probit link). The two methods then maximize, over \boldsymbol{\eta}_i:
method = "EBM"(empirical Bayes modal): the log posterior, \log \phi(\boldsymbol{\eta}_i;\, \boldsymbol{\mu}_{\eta}(\mathbf{x}_i), \boldsymbol{\Psi}^{*}) + \sum_{p} \log f(y_p\mid \boldsymbol{\eta}_i), i.e., the posterior mode (MAP). This is the categorical analogue of the regression method.method = "ML": the log-likelihood \sum_{p} \log f(y_p\mid \boldsymbol{\eta}_i) alone, the analogue of Bartlett scoring. Because an all-extreme response pattern drives the unpenalized maximum to \pm\infty, lavaan adds a very vague quadratic penalty (\tfrac{1}{2}\,\boldsymbol{\eta}_i^{\prime} (10^{-5}\,\mathbf{I})\,\boldsymbol{\eta}_i, after centering) purely to keep the optimum finite.
See Skrondal and Rabe-Hesketh (2004) (Chapter 7) for a general treatment of empirical Bayes and ML scoring in latent variable models. Some practical notes on the implementation:
Each case is a small unconstrained optimization problem, solved with a quasi-Newton method (BFGS by default; the
optim_methodargument oflavPredict()selects the routine, see the implementation notes at the end of this chapter). When the residual covariance matrix \boldsymbol{\Theta} is diagonal, the objective is the sum of the univariate terms of Equation 13.22 (conditional independence of the indicators given \boldsymbol{\eta}_i). Residual covariances are respected: the indicators are split into blocks (the connected components of the nonzero pattern of \boldsymbol{\Theta}), and the contribution of a block with two or more indicators is their joint density given \boldsymbol{\eta}_i, in which the numeric indicators are multivariate normal and, given these, the latent responses of the ordered indicators are normal, so that the probability of the observed categories is a bivariate normal probability for two ordered indicators, and a multivariate normal probability for three or more, computed by a GHK simulator with fixed integration points (no random numbers; smooth in \boldsymbol{\eta}_i). Missing values inside a block use the marginal density of the observed indicators, and a block whose \boldsymbol{\Theta} submatrix is not positive definite is treated as independent, with a warning. The argumentlocal_independence = TRUEignores the residual covariances and restores the product of univariate terms.Cases that share the same response pattern (and covariate values) have identical objectives, so lavaan optimizes once per unique pattern and copies the result, often an order-of-magnitude saving with ordinal data. The remaining optimizations are embarrassingly parallel; the
parallel,ncpus, andclarguments expose this (the default,parallel = "auto", forks only when the number of unique patterns is large enough to amortize the overhead). The computation is deterministic, so the parallel settings never change the result.With
se = "standard", the standard errors come from the curvature of the objective at the optimum: the variance matrix is the inverse of the Hessian of the negative log-posterior (EBM) or negative log-likelihood (ML), that is, a Laplace approximation. Unlike the continuous case, the curvature depends on the response pattern, so the"se"attribute is a full N\times M matrix, andacov = "standard"returns one matrix per case.With
transform = TRUE, the correlation-preserving transformation of Section 13.3.6 is available here too. Because the discrete scores have no closed-form variance, the transformation uses their empirical variance matrix, so the sample variance of the transformed scores matches the model-implied \boldsymbol{\Psi} (given the covariates) exactly.A zero on the diagonal of \hat{\boldsymbol{\Theta}} makes Equation 13.22 degenerate; lavaan stops with an error in that case.
HSord <- HolzingerSwineford1939
HSord[, paste0("x", 1:9)] <- lapply(HSord[, paste0("x", 1:9)],
function(x) cut(x, 4, labels = FALSE))
fitc <- cfa(model, data = HSord, ordered = paste0("x", 1:9))
fsc <- lavPredict(fitc, method = "EBM", se = "standard")
head(fsc, 3) visual textual speed
[1,] -0.2652133 0.004502983 0.2079488
[2,] 0.1412391 -0.636892222 0.6600174
[3,] -0.8494136 -1.563581417 -0.4398845
head(attr(fsc, "se")[[1]], 3) visual textual speed
[1,] 0.4318476 0.3016935 0.2872669
[2,] 0.4440255 0.3417488 0.2754443
[3,] 0.4434650 0.4217531 0.2907197
13.3.10 Multilevel models
For a two-level model, there are latent variables at both levels, and the level argument selects which set is scored (level = 1, the default, for the within level; level = 2 for the between level). The computation is a two-stage empirical Bayes procedure:
The latent group means of the within-level variables are predicted first, as their posterior means given the cluster’s data (including any between-only variables, which are observed at the cluster level and enter the next stage as they are); this is the same E-step computation used by the EM algorithm for the saturated multilevel model.
For
level = 2, these posterior means are then treated as the “data” for the between-level measurement model, and the usual linear map Equation 13.3 is applied with the between-level model matrices. Forlevel = 1, each observation is centered at its cluster’s posterior mean, and the within-level map is applied to the centered data. Both methods are accepted at both levels; withmethod = "Bartlett"the Bartlett map replaces the regression map in this stage, and the posterior-mean interpretation below applies to the regression method.
When the model was fitted with missing = "ml", the first stage conditions on all observed data in the cluster and simultaneously replaces the missing values by their posterior means; because the second stage is linear, the resulting factor scores are the exact posterior means given all observed data (see appendix E.6).
model2l <- '
level: within
fw =~ y1 + y2 + y3
level: between
fb =~ y1 + y2 + y3
'
fit2l <- sem(model2l, data = Demo.twolevel, cluster = "cluster")
fs_w <- lavPredict(fit2l, level = 1) # one row per observation
fs_b <- lavPredict(fit2l, level = 2) # one row per cluster
nrow(fs_w); nrow(fs_b)[1] 2500
[1] 200
Models with random slopes are handled separately at the start of lavPredict(): with level = 2, the posterior means of all cluster-level latent variables, including the random slopes, are returned, and se = "standard" yields their posterior standard deviations; with level = 1, the within-level factor scores are computed conditionally on those posterior means. In this setting only type = "lv" with method = "EBM" is supported, newdata is not accepted, no standard errors are available at level 1, and the fsm, mdist, rel, transform, and append_data options are not available in version 0.7-4.
13.3.11 Higher-order factors
A higher-order factor has no observed indicators of its own: its column in \boldsymbol{\Lambda} is empty. For the regression method this causes no problem, because the weights \boldsymbol{\Psi}^{*}\boldsymbol{\Lambda}^{\prime}\boldsymbol{\Sigma}^{-1} involve the higher-order factor only through \boldsymbol{\Psi}^{*}. The Bartlett map, however, would return an all-zero row. lavaan handles this by collapsing the measurement chain, exactly as in the SAM approach: the loadings of the latent indicators are absorbed into
\boldsymbol{\Lambda}^{\star} = \boldsymbol{\Lambda}\,(\mathbf{I} - \mathbf{B}^{\star})^{-1}, \tag{13.23}
where \mathbf{B}^{\star} retains only the rows of \mathbf{B} that belong to latent indicators (the higher-order loadings), so that \boldsymbol{\Lambda}^{\star} expresses the observed indicators directly in terms of the top-layer factors. The Bartlett rows for the higher-order factors are then taken from the (Sigma-form) Bartlett map based on the relevant columns of \boldsymbol{\Lambda}^{\star}, while the rows of the first-order factors are left untouched. The resulting coefficient matrix no longer satisfies \mathbf{A}\boldsymbol{\Lambda}= \mathbf{I} row by row, so the Bartlett shortcut of Equation 13.21 does not apply to the higher-order rows; their standard errors come from the general expression Equation 13.20, as for all other scores.
model_g <- '
visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9
g =~ visual + textual + speed
'
fit_g <- cfa(model_g, data = HolzingerSwineford1939)
head(lavPredict(fit_g, method = "Bartlett"), 3) visual textual speed g
[1,] -1.36953899 -0.09955028 0.2318376 -0.84328966
[2,] 0.07592924 -1.19815114 0.9886435 0.05692248
[3,] -0.56109948 -2.10473949 -1.1216760 -1.38126005
13.4 Factor scores as case diagnostics
Factor scores are the basis for the casewise outlier diagnostics of Section 10.10: the leverage Mahalanobis distance of Section 10.10.2 is the M-distance of the Bartlett scores in the metric of Equation 13.13 (first expression), and the outlier M-distance of Section 10.10.3 is based on the corresponding casewise residuals. Rather than repeating that material, we only point out how it connects to lavPredict():
Adding
mdist = TRUEto alavPredict()call attaches the squared M-distances as the"mdist"attribute: of the factor scores whentype = "lv", of the casewise residuals whentype = "resid", and of the fitted values whentype = "yhat". For continuous data, requestingmdistforcesfsm = TRUEinternally, because the distances need the weight matrix to construct the variance matrix of the scored quantities.The
lavInspect()shortcuts"mdist_fs","mdist_resid","mdist2_fs", and"mdist2_resid"used in Section 10.10 are implemented aslavPredict()calls withmethod = "ML"(Bartlett) andmdist = TRUE; for ordered data they call the categorical generalization below directly, and the unsquared versions are then expected distances rather than square roots of the squared ones.For ordered categorical data, the distances are generalized following Mansolf and Reise (2017): each distance is replaced by its expectation over the region of the latent-response vector \mathbf{y}^{\star} consistent with the observed responses, approximated by Monte Carlo integration with
mdist_draws(default 2000) draws per distinct response pattern. This computation uses a vectorized GHK importance sampler, and reduces exactly to the continuous formulas when all variables are continuous and observed. Because random draws are involved,set.seed()is needed for reproducibility.
fs <- lavPredict(fit, method = "ML", mdist = TRUE)
head(attr(fs, "mdist")[[1]]) # squared leverage distances[1] 2.270885 3.971682 5.494760 1.489545 1.067721 5.892432
13.5 Predicting observed outcomes: lavPredictY()
lavPredict() does not perform regression-style prediction by design: it scores the latent variables, and its type = "yhat" merely maps those scores back to the indicators. When the goal is to predict the values of some observed outcome variables from other observed variables (for new cases, in the ordinary out-of-sample sense), the function to use is lavPredictY(), introduced following de Rooij et al. (2023).
13.5.1 Conditional-mean prediction
The idea is as follows. A fitted SEM delivers a model-implied joint mean vector \hat{\boldsymbol{\mu}} and covariance matrix \hat{\boldsymbol{\Sigma}} for all observed variables. Partition the variables into a target set y (the ynames argument) and a predictor set x (xnames), with the corresponding blocks \hat{\boldsymbol{\mu}}_y, \hat{\boldsymbol{\mu}}_x, \hat{\boldsymbol{\Sigma}}_{yx}, and \hat{\boldsymbol{\Sigma}}_{xx}. Under joint normality, the best prediction of the y-values of case i given its x-values is the conditional mean
\hat{\mathbf{y}}_{i} = \hat{\boldsymbol{\mu}}_y + \hat{\boldsymbol{\Sigma}}_{yx}\,\hat{\boldsymbol{\Sigma}}_{xx}^{-1}\, (\mathbf{x}_i - \hat{\boldsymbol{\mu}}_x), \tag{13.24}
which is exactly what method = "conditional.mean" (currently the only method) computes. Several details should be noted:
The partitioning into y and x is chosen by the user:
ynamesdefaults to the model’s endogenous observed variables ("ov_y") andxnamesto the exogenous ones ("ov_x"), but any two sets of observed variables can be used, including indicators of latent variables, as in the example below.The model enters only through \hat{\boldsymbol{\mu}} and \hat{\boldsymbol{\Sigma}}: a more restrictive (but correct) model yields more stable estimates of the prediction weights. If the model is saturated (\mathrm{df} = 0), Equation 13.24 reproduces ordinary least squares prediction exactly.
When the model was fitted with
conditional_x = TRUE, the implied moments are first converted back to the joint scale, so that Equation 13.24 always operates on the joint distribution, and the exogenous covariates can be named inxnameslike any other variable.If the model has no mean structure, the saturated sample means are used for \hat{\boldsymbol{\mu}}; alternatively,
force_zero_mean = TRUEsets the mean vector to zero.newdatafollows the same conventions as inlavPredict(); for multigroup models it can also be a list with one data frame per group (withNULLentries for groups to skip), which allows group-specificynames/xnames.newdatais processed withmissing = "ml.x"internally, so that incomplete cases are kept and the output stays aligned with the rows ofnewdata; a case with a missing predictor receivesNApredictions (no imputation is done). Models with ordered indicators and multilevel models are not supported in version 0.7-4.
Predicting the 1965 democracy indicators from the 1960 variables in the political democracy example:
yn <- c("y5", "y6", "y7", "y8")
xn <- c("x1", "x2", "x3", "y1", "y2", "y3", "y4")
head(lavPredictY(fitPD, ynames = yn, xnames = xn), 3) y5 y6 y7 y8
[1,] 2.427903 -0.4303205 2.722847 0.4960760
[2,] 2.548290 -0.2788161 2.877242 0.6537553
[3,] 7.849819 6.3930350 9.676372 7.5975374
13.5.2 Regularization and cross-validation
Out-of-sample prediction accuracy can often be improved by shrinking the prediction weights. lavPredictY() supports a ridge-type penalty through the lambda argument: the predictor-block covariance matrix in Equation 13.24 is replaced by \hat{\boldsymbol{\Sigma}}_{xx} + \lambda\,\mathbf{I}, which damps the weights of nearly-collinear predictors. The companion function lavPredictY_cv() chooses \lambda by k-fold cross-validation (the data must be passed explicitly through its data argument): the data are randomly partitioned into n_folds folds; for each fold, the model is refitted (via update()) on the remaining data, and the held-out fold is predicted for every value in lambda_seq; the \lambda with the smallest average mean squared error is returned as lambda.min (the results table is sorted by that error, not by \lambda). Because the folds are drawn at random, a seed is needed for reproducibility:
set.seed(123)
cv <- lavPredictY_cv(fitPD, data = PoliticalDemocracy,
ynames = yn, xnames = xn,
n_folds = 5, lambda_seq = seq(0, 2, 0.5))
cv$results lambda mse
3 1.0 4.364186
2 0.5 4.367600
4 1.5 4.368890
5 2.0 4.378582
1 0.0 4.390885
cv$lambda.min[1] 1
The selected value is then passed on to lavPredictY(..., lambda = cv$lambda.min), typically with genuinely new data in newdata. Note that the cross-validation loop refits the model in every fold, so the reported MSE reflects the whole procedure, not just the prediction rule.
13.5.3 Residuals: lavResidualsY()
The public function lavResidualsY() returns the casewise prediction residuals (the observed minus the predicted values of the y-variables), using the same arguments (and the same internal prediction code) as lavPredictY():
ry <- lavResidualsY(fitPD, ynames = yn, xnames = xn)
head(ry, 3) y5 y6 y7 y8
[1,] -1.1779029 0.4303205 1.0035130 2.8372570
[2,] 3.7017100 1.3788161 3.7894244 0.0832437
[3,] 0.9001814 1.7010260 0.3236256 0.6142716
These residuals are on the observed scale and are the natural input for inspecting prediction quality variable by variable, or for computing out-of-sample error measures on a test set (via newdata).
13.6 Factor scores in two-step analyses
A common workflow is to split a SEM into two steps: first fit only the measurement model(s), compute factor scores, and then use those scores as if they were the latent variables in a second-step regression or path analysis. This is known as factor score regression (FSR), and in its naive form it produces biased estimates of the structural parameters, a fact that has been known for a long time but is still often overlooked.
The source of the bias follows directly from Section 13.2. Consider the simplest structural relation \eta_y = \gamma\,\eta_x + \zeta, and suppose we regress scores \hat{\eta}_y on scores \hat{\eta}_x. The probability limit of the OLS slope is \text{Cov}(\hat{\eta}_y, \hat{\eta}_x) / \text{Var}(\hat{\eta}_x), and neither ingredient matches its latent target: regression scores have too little variance (Equation 13.6), Bartlett scores too much (Equation 13.13), and the cross-covariance contains measurement-error terms whenever the two scores share indicators or weights. Skrondal and Laake (2001) showed that one specific procedure avoids the bias in this setting: compute the scores from separate measurement models per block, use the regression method for the exogenous factor and the Bartlett method for the endogenous factor. Then \text{Cov}(\hat{\eta}_x^{R}, \eta_x) = \text{Var}(\hat{\eta}_x^{R}) (Equation 13.8) makes the denominator self-correcting, while the Bartlett score on the left-hand side is conditionally unbiased and its measurement error is uncorrelated with the x-block. A small demonstration with the political democracy data:
fit_sem <- sem('ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem60 ~ ind60', data = PoliticalDemocracy)
coef(fit_sem)["dem60~ind60"] # one-step SEM benchmarkdem60~ind60
1.439316
fit_x <- cfa('ind60 =~ x1 + x2 + x3', data = PoliticalDemocracy)
fit_y <- cfa('dem60 =~ y1 + y2 + y3 + y4', data = PoliticalDemocracy)
f_x_r <- lavPredict(fit_x, method = "regression")[, 1]
f_y_b <- lavPredict(fit_y, method = "Bartlett")[, 1]
f_y_r <- lavPredict(fit_y, method = "regression")[, 1]
coef(lm(f_y_r ~ f_x_r))[2] # naive FSR: attenuated f_x_r
1.283975
coef(lm(f_y_b ~ f_x_r))[2] # Skrondal-Laake recipe: close to SEM f_x_r
1.447867
The Skrondal–Laake procedure, however, is tied to this particular configuration (exogenous predictors, endogenous outcome, separate blocks); it does not generalize to arbitrary structural models. The general solution is to correct not the scores but their moments. Because the mapping from data to scores is a known linear map \mathbf{A}, the model-implied moments of the scores are known functions of the latent moments, namely \text{Var}(\hat{\boldsymbol{\eta}}) = \mathbf{A}\boldsymbol{\Sigma}\mathbf{A}^{\prime} and \text{Cov}(\hat{\boldsymbol{\eta}}, \boldsymbol{\eta}) = \mathbf{A}\boldsymbol{\Lambda}\boldsymbol{\Psi}^{*}, and these relations can be inverted to recover consistent estimates of the latent variance matrix from the (biased) variance matrix of the factor scores. The idea was first developed by Wall and Amemiya (2000), in a paper on polynomial structural models: their estimator uses Bartlett scores whose measurement-error moments are subtracted out, and for a linear structural model it reduces exactly to the correction that Croon (2002) derived independently two years later. For a long time the earlier paper went unnoticed in the factor score literature (its focus on nonlinear effects hid the general result), which is why the method became known as the “Croon correction”; the name has remained, but the credit belongs to Wall and Amemiya as much as to Croon. Simulation evidence (Devlieger et al., 2016) shows that corrected factor score regression matches full-information SEM in terms of bias while often being more robust in small samples. This moment-correction idea, applied block by block with the factor score matrix from fsm = TRUE as the central element, is exactly the foundation of the structural-after-measurement (SAM) approach implemented in lavaan’s sam() function, which is the topic of Chapter 18. The practical advice is therefore as follows: factor scores are well suited for description, visualization, ranking, and diagnostics, but if the goal is to estimate structural parameters in a stepwise fashion, do not regress raw factor scores on each other; use sam() instead.
13.7 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. All of the chapter’s computations pass through a small number of internal functions in the file lav_predict.R (with the categorical generalization of the Mahalanobis distances in lav_predict_mdist.R and lavPredictY() in lav_predict_y.R); knowing the pipeline makes it easy to locate any specific computation in the source.
lavPredict()is a thin public wrapper: it validates the object, interceptsefaListinput and random-slope models (the latter are handed tolav_mvn_cl_rs_eb(),lav_mvnorm_cluster_rs.R), and callslav_predict_internal(). The internal version takes the model, the data, and the implied moments as separate arguments, so that it can work before a full lavaan object exists, but in the current release it is called only fromlavPredict(); the casewise-robust variance code of the standard-error chapter calls the lower-levellav_predict_eta_normal()directly.lav_predict_internal()normalizes thetypealiases, processesnewdata(building a freshlavDataobject when needed), and dispatches ontype. Fortype = "lv"it callslav_predict_eta(); for"yhat"/"resid"it callslav_predict_yhat(); for"fy",lav_predict_fy(). It also strips the dummy latent variables from the output, attaches thefsm,rel,se,acov, andmdistattributes, appliesappend_data/assemble, and sets the labels.lav_predict_eta()normalizes themethodaliases and branches on the data type: if all observed variables are numeric, the closed-formlav_predict_eta_normal()is used; otherwise, the per-case optimizerlav_predict_eta_ebm_ml(). The latter evaluates the casewise objective throughlav_predict_fy_eta_i()and minimizes it with R’soptim()(optim_method = "bfgs", the current default) ornlminb()(optim_method = "nlminb").lav_predict_eta_normal()assembles the ingredients from the model matrices (lav_model_lambda(),lav_model_veta(),lav_model_eeta(),lav_model_ey(), and the model-impliedlavimplied$cov; with exogenous covariates, the case-conditionallav_model_eetax()andlav_model_vetax()), builds the coefficient matrix in the local helpercompute_fsc()(with the Bartlett/regression switch, the pseudo-inverse fallbacklav_predict_solve(), and the higher-order collapse), and computes the prediction variance incompute_fscov(). Missing patterns, groups, and levels are handled by looping with the block mappinglav_predict_block_idx()(block b = (g-1) \times \texttt{nlevels} + \texttt{level}); per missing pattern, the inverse of the observed block of \hat{\boldsymbol{\Sigma}} is obtained from the full inverse bylav_mat_sym_inverse_update(). The determinacy values of Section 13.2.5 are computed here as well, and so are the two-level scores: the first stage calls the E-step routines of the multilevel EM algorithm,lav_mvn_cl_em_estep_ranef()(complete data) andlav_mvn_cl_mi_estep_ranef()(missing = "ml"), inlav_mvnorm_cluster.Randlav_mvnorm_cluster_missing.R.The correlation-preserving transformations are implemented in
lav_predict_tmat_green()andlav_predict_tmat_det(), with single-block versions that are reused by the local SAM code.lav_predict_yhat()computes the predicted indicator values throughlav_model_yhat(). The continuous Mahalanobis distances are computed inline inlav_predict_internal(); the categorical Mahalanobis distances are computed bylav_predict_mdist_cat().lavPredictY()delegates tolav_predict_y_conditional_mean(), converting conditional moments to the joint scale withlav_model_cond2joint_sigma()andlav_model_cond2joint_mu()(lav_model_compute.R).
The key design point is that the model-implied moments feed the weights: nothing in the pipeline touches the sample covariance matrix directly. Every weight matrix is a function of (\hat{\boldsymbol{\Lambda}}, \hat{\boldsymbol{\Psi}}^{*},
\hat{\boldsymbol{\Theta}}, \hat{\boldsymbol{\Sigma}}) evaluated at \hat{\boldsymbol{\vartheta}}, which is why factor scores can be computed for newdata, per missing pattern, or per level, without involving the estimation code again. One deliberate exception concerns sampling weights: a case’s factor score must not depend on its own sampling weight, so the weights enter only through the (weighted) parameter estimates and the weighted means used for centering. The casewise computation itself is unweighted.