Structural equation models
A proposed set of relationships among variables should have consequences for the data. A measurement model relates observed responses to latent variables. A structural model describes relationships among those latent variables. A full structural equation model (SEM) combines the two: uncertainty about the measurement of a construct enters the estimation of its relationships with other constructs. Its equations specify a probability distribution whose implications can be assessed against observed means and covariances. Agreement with those moments does not establish a causal direction. The chapter writes measurement and structural equations in one matrix notation, derives the means and covariances they imply, and fits those moments to data, with extensions to incomplete responses and to measures of fit.
7.1 RAM notation for measurement and structural equations
Consider nine continuous responses from each independently sampled person. Responses $y_1,y_2,y_3$ measure a latent variable $\xi$; $y_4,y_5,y_6$ measure $\eta_1$; and $y_7,y_8,y_9$ measure $\eta_2$. Suppress the person index and write $y=(y_1,\ldots,y_9)^\top$ for one person’s responses and $f=(\xi,\eta_1,\eta_2)^\top$ for that person’s latent variables. Each response has an intercept, a loading on its assigned factor, and a response-specific error. The measurement model is
\[y=\nu+\Lambda f+e,\qquad \Lambda=\begin{pmatrix} 1&0&0\\ \lambda_2&0&0\\ \lambda_3&0&0\\ 0&1&0\\0&\lambda_5&0\\0&\lambda_6&0\\ 0&0&1\\0&0&\lambda_8\\0&0&\lambda_9 \end{pmatrix},\qquad \operatorname{Var}(e)=\Theta=\operatorname{diag}(\theta_1,\ldots,\theta_9).\]The vector $\nu=(\nu_1,\ldots,\nu_9)^\top$ contains the response intercepts, and the $9\times3$ matrix $\Lambda$ contains the factor loadings. Its rows correspond to responses and its columns to $\xi,\eta_1,\eta_2$, in that order. The fixed zeros specify that each response depends directly on only its assigned factor. For example, row two contains $\lambda_2$ in the first column and zeros in the other two. The six symbols $\lambda_2,\lambda_3,\lambda_5,\lambda_6,\lambda_8,\lambda_9$ denote free loadings; the three entries equal to one are fixed loadings. Intercepts, loadings and variance parameters describe the population and are shared across people. The values of $f$ and $e$ vary from person to person.
Assume that the nine errors in $e=(e_1,\ldots,e_9)^\top$ have joint distribution $N_9(0,\Theta)$ and are independent of $f$. Then $E(y_2\mid\xi)=\nu_2+\lambda_2\xi$. The intercept $\nu_2$ is the expected response at $\xi=0$, in the units of $y_2$. The loading $\lambda_2$ is the change in that expectation per unit of $\xi$, so its units are response units per factor unit. At the same factor value, increasing the intercept raises the conditional mean by the same amount. Changing the loading changes how the mean depends on the factor. The free loadings may be positive, zero or negative; a negative loading makes the response’s conditional mean decrease as its assigned factor increases.
The diagonal entry $\theta_j$ is $\operatorname{Var}(e_j)$ and also $\operatorname{Var}(y_j\mid f)$, in squared units of response $j$. It measures variation around the response’s conditional mean. This variation can include response-specific influences and measurement error; the equation does not separate those sources. With the other parameters fixed, increasing $\theta_j$ increases response $j$’s variance without changing its covariances with other responses. Diagonal $\Theta$, together with normality, makes the response errors mutually independent. Responses can nevertheless be associated after averaging over the latent variables.
The first loading on each factor is fixed at one. This marker constraint defines the factor’s unit through its marker response and fixes its sign. A one-unit increase in $\xi$ changes the conditional mean of $y_1$ by one response unit; the marker responses for $\eta_1$ and $\eta_2$ are $y_4$ and $y_7$. Thus $\lambda_2$ is expressed in units of $y_2$ per unit of $y_1$ on this factor scale. The marker response still has its own error: $y_1=\nu_1+\xi+e_1$, so its observed value is not the person’s factor value. This constraint sets the factor’s unit without fixing its variance. A factor unit is therefore not necessarily one standard deviation, and the marker constraint does not require every other loading to be positive.
The latent variables also have equations. The variable $\xi$ is exogenous in the structural model: no other variable in that model predicts it. The variables $\eta_1$ and $\eta_2$ are endogenous because each is an outcome of a structural regression. Their equations are
\[\xi=u,\qquad \eta_1=a\xi+\zeta_1,\qquad \eta_2=c'\xi+b\eta_1+\zeta_2.\]The centered random variable $u$ supplies the variation in $\xi$. The disturbances $\zeta_1$ and $\zeta_2$ are the parts of the endogenous latent variables left after subtracting the specified predictor terms. Assume that $u,\zeta_1,\zeta_2$ are mutually independent normal variables, are independent of all response errors, and have variances $\operatorname{Var}(u)=\phi$, $\operatorname{Var}(\zeta_1)=\psi_1$, and $\operatorname{Var}(\zeta_2)=\psi_2$. Both disturbances have mean zero. These structural disturbances describe unexplained variation in the latent outcomes; the errors $e_j$ describe variation in their observed indicators.
The structural intercepts are fixed to zero. Together with the centered disturbances, this gives zero means for all three factors and sets their origins. Consequently $E(y)=\nu$, so the nine response intercepts are also their marginal means. This equality depends on the zero latent means. The general measurement equation would give $E(y)=\nu+\Lambda E(f)$ if those means were nonzero.
The coefficient $a$ is the change in $E(\eta_1\mid\xi)=a\xi$ for a one-unit increase in $\xi$. It has units of $\eta_1$ per unit of $\xi$, determined here by the marker scales of $y_4$ and $y_1$. For the second regression, $E(\eta_2\mid\xi,\eta_1)=c^{\prime}\xi+b\eta_1$. The coefficient $b$ is the change in this expectation per unit of $\eta_1$ at a fixed $\xi$, in units of $\eta_2$ per unit of $\eta_1$. The coefficient $c^{\prime}$ is the change per unit of $\xi$ at a fixed $\eta_1$, in units of $\eta_2$ per unit of $\xi$. The prime in $c^{\prime}$ is part of the coefficient’s label; it does not denote a derivative.
These are unstandardized regression coefficients, so their numerical sizes depend on the marker-defined factor units. They are not correlations and need not lie between -1 and 1. A zero $c^{\prime}$ removes the direct path from $\xi$ to $\eta_2$ while allowing an association through $\eta_1$. To distinguish these contributions, substitute the equation for $\eta_1$ into that for $\eta_2$:
\[\eta_2=(c'+ab)\xi+b\zeta_1+\zeta_2.\]Thus $ab$ is the indirect path coefficient through $\eta_1$, $c^{\prime}$ the direct path coefficient, and $c^{\prime}+ab$ the total coefficient of $\xi$ in this reduced equation. The product $ab$ combines a change in $\eta_1$ per unit of $\xi$ with a change in $\eta_2$ per unit of $\eta_1$. Both $ab$ and $c^{\prime}$ consequently have units of $\eta_2$ per unit of $\xi$, which permits their sum. Averaging over the disturbances gives $E(\eta_2\mid\xi)=(c^{\prime}+ab)\xi$. A causal interpretation additionally requires a defensible direction of influence and assumptions excluding unmodeled common causes and relevant measurement misspecification. The normal covariance likelihood alone supplies neither.
The parameter $\phi$ is the marginal variance of the exogenous factor $\xi$, in squared units of its marker scale. It describes how much $\xi$ varies across people. The parameter $\psi_1$ is the conditional variance $\operatorname{Var}(\eta_1\mid\xi)$, in squared units of $\eta_1$. At a given $\xi$, people differ in $\eta_1$ through $\zeta_1$. Across all people, variation transmitted from $\xi$ also contributes, giving $\operatorname{Var}(\eta_1)=a^2\phi+\psi_1$.
Likewise, $\psi_2=\operatorname{Var}(\eta_2\mid\xi,\eta_1)$ is the variance remaining after both predictors in the second regression, in squared units of $\eta_2$. If only $\xi$ is specified, variation in $\zeta_1$ still reaches $\eta_2$ through $b$, so $\operatorname{Var}(\eta_2\mid\xi)=b^2\psi_1+\psi_2$. Its marginal variance also includes variation transmitted from $\xi$: $\operatorname{Var}(\eta_2)=(c^{\prime}+ab)^2\phi+b^2\psi_1+\psi_2$. Fixing an endogenous disturbance variance at one would therefore not standardize its marginal factor variance. The variances $\theta_j$, $\phi$ and $\psi_k$ describe population variation in responses and latent variables. They must be nonnegative for an admissible model; the simulated population uses strictly positive values. Sampling variances of estimated loadings or path coefficients are different quantities, obtained from the information matrix later in the chapter.
Reticular action model (RAM) notation collects the equations into
\[v=m+Av+\varepsilon,\qquad v=(y_1,\ldots,y_9,\xi,\eta_1,\eta_2)^\top.\]For an arrow from variable $j$ to variable $i$, the coefficient occupies row $i$, column $j$ of the $12\times12$ matrix $A$. The loading $\lambda_2$ is $A_{2,10}$, and the structural coefficient $b$ is $A_{12,11}$. Reversing these indices would reverse the predictor and outcome in the equation. Its lower-right $3\times3$ block $H$ contains the structural coefficients among the factors, in their stated order. Here the complete arrays are
\[A=\begin{pmatrix}0_{9\times9}&\Lambda\\0_{3\times9}&H\end{pmatrix},\quad H=\begin{pmatrix}0&0&0\\a&0&0\\c'&b&0\end{pmatrix},\quad S=\operatorname{Var}(\varepsilon)=\operatorname{diag}(\theta_1,\ldots,\theta_9,\phi,\psi_1,\psi_2),\] \[m=(\nu^\top,0,0,0)^\top,\qquad F=(I_9\ \ 0_{9\times3}).\]The full disturbance vector is $\varepsilon=(e_1,\ldots,e_9,u,\zeta_1,\zeta_2)^\top$. The $12\times12$ matrix $S$ is its covariance, rather than the covariance of the twelve variables in $v$. Its final three diagonal entries describe variation in the factor equations; they are not additional errors attached to the observed responses. In this model $S$ is diagonal even though the factors are correlated. Their covariances arise through the structural paths. More generally, off-diagonal entries of $S$ permit correlated disturbances. The vector $m$ collects the nine response intercepts and three fixed structural intercepts. The known $9\times12$ selection matrix $F$ extracts the observed responses from $v$ and contains no estimated parameters.
Run the accompanying code from the book directory. The setup loads the book’s functions and defines two recording functions: record_check() saves a numerical discrepancy with its stated tolerance, and record_review() saves whether a stated review condition is met. Neither changes an estimate. Inputs are saved under data/source/ch07, fitted objects under data/derived/ch07, and these check records under results/ch07/application. Subsequent blocks display the RAM routines at the points where their calculations are developed. The setup function start_application() in code/lib/application_run.R is the same for every chapter with an empirical application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
start_application <- function(chapter) {
stopifnot(length(chapter) == 1L, chapter %in% c(7L, 10L, 11L, 12L, 14L, 15L, 16L))
if (!file.exists("code/lib/sem.R")) stop("Run this script from the book directory.")
if (dir.exists(".R-library")) .libPaths(c(normalizePath(".R-library"), .libPaths()))
options(width = 110, digits = 7, warn = 1)
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
common <- c("result", "stability", "logit", "differentiation", "lbfgsb",
"line_search", "quasi_newton", "newton", "transforms", "dogleg", "factored_secant", "integration")
additional <- list(`7` = c("factor", "sem"), `10` = "irt",
`11` = c("irt", "mixed_laplace"), `12` = "mixtures",
`14` = c("simulation", "mcmc", "stochastic_items", "inference", "multidim_items"),
`15` = c("factor", "sem", "inference"), `16` = c("posterior_checks", "mixed_gibbs"))
for (file in c(common, additional[[as.character(chapter)]]))
sys.source(file.path("code", "lib", paste0(file, ".R")), envir = parent.frame())
chapter_name <- sprintf("ch%02d", chapter)
for (directory in c(file.path("data/source", chapter_name), file.path("data/derived", chapter_name)))
dir.create(directory, recursive = TRUE, showWarnings = FALSE)
run_name <- paste0(format(Sys.time(), "%Y%m%d-%H%M%S", tz = "Asia/Seoul"), "-", Sys.getpid())
record_directory <- file.path("results", chapter_name, "application", run_name)
dir.create(record_directory, recursive = TRUE, showWarnings = FALSE)
checks <- data.frame(check = character(), discrepancy = numeric(), tolerance = numeric(), passed = logical())
review <- data.frame(check = character(), passed = logical(), detail = character())
record_check <- function(name, discrepancy, tolerance) {
stopifnot(length(discrepancy) == 1L, length(tolerance) == 1L)
checks[nrow(checks) + 1L, ] <<- list(name, discrepancy, tolerance,
is.finite(discrepancy) && discrepancy <= tolerance)
write.csv(checks, file.path(record_directory, "validation.csv"), row.names = FALSE)
invisible(tail(checks$passed, 1L))
}
record_review <- function(name, passed, detail) {
review[nrow(review) + 1L, ] <<- list(name, isTRUE(passed), as.character(detail))
write.csv(review, file.path(record_directory, "review-flags.csv"), row.names = FALSE)
invisible(isTRUE(passed))
}
list(record_check = record_check, record_review = record_review,
record_directory = record_directory)
}
It accepts the chapters that have such an application and stops unless R runs in the book directory. It sets the random-number methods, loads the common library files and those of the chapter into the calling session, and creates the chapter’s folders for inputs and fitted objects. Each run writes its records to a new folder under results/ch07/application. The function record_check() adds a row with the name, the discrepancy, the tolerance and whether a finite discrepancy is at most the tolerance, and rewrites validation.csv; record_review() adds a row to review-flags.csv in the same way.
1
2
3
4
5
6
7
8
9
10
11
source("code/lib/application_run.R", local = TRUE)
application <- start_application(7L)
record_check <- application$record_check
record_review <- application$record_review
replications <- as.integer(Sys.getenv("STAT_BOOK_SEM_REPLICATIONS", "200"))
stopifnot(length(replications) == 1L, !is.na(replications), replications > 0L)
options(width = 110, digits = 7, warn = 1)
for (file in c("result", "differentiation", "line_search", "quasi_newton",
"dogleg", "transforms", "factor", "sem")) {
source(file.path("code", "lib", paste0(file, ".R")))
}
The function ram_spec() stores the four arrays and a parameter table. Each row of the table names an array, a row, a column and the parameter assigned to that position. ram_expand() fills those positions from a parameter vector in the recorded order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
ram_spec <- function(A, S, m, F, parameter_table, transforms) {
d <- nrow(A)
stopifnot(is.matrix(A), identical(dim(A), c(d, d)),
is.matrix(S), identical(dim(S), c(d, d)), isSymmetric(S),
length(m) == d, is.matrix(F), ncol(F) == d, nrow(F) >= 1,
all(is.finite(c(A, S, m, F))), all(F %in% c(0, 1)),
all(rowSums(F) == 1), all(colSums(F) <= 1),
identical(names(parameter_table), c("matrix", "row", "col", "parameter")),
all(parameter_table$matrix %in% c("A", "S", "m")),
all(parameter_table$row %in% seq_len(d)), all(parameter_table$col %in% seq_len(d)),
all(parameter_table$col[parameter_table$matrix == "m"] == 1),
all(parameter_table$row[parameter_table$matrix == "S"] >= parameter_table$col[parameter_table$matrix == "S"]),
!anyDuplicated(parameter_table[c("matrix", "row", "col")]),
!is.null(names(transforms)), !anyDuplicated(names(transforms)),
setequal(parameter_table$parameter, names(transforms)),
all(transforms %in% c("identity", "log", "tanh")))
if (qr(diag(d) - A)$rank < d) stop("I - A is not invertible.")
list(A = A, S = S, m = m, F = F, parameter_table = parameter_table,
parameters = names(transforms), transforms = transforms, dimension = d)
}
ram_expand <- function(theta, spec) {
stopifnot(length(theta) == length(spec$parameters), all(is.finite(theta)))
values <- setNames(theta, spec$parameters)
out <- spec[c("A", "S", "m", "F")]
for (k in seq_len(nrow(spec$parameter_table))) {
pos <- spec$parameter_table[k, ]
value <- values[[pos$parameter]]
if (pos$matrix == "m") out$m[pos$row] <- value else {
out[[pos$matrix]][pos$row, pos$col] <- value
if (pos$matrix == "S") out$S[pos$col, pos$row] <- value
}
}
out
}
The checks in ram_spec() require compatible dimensions, a symmetric disturbance covariance, valid parameter locations, and an observation selector with exactly one unit per row and at most one per column. A covariance is listed once in the lower triangle; ram_expand() fills both symmetric entries. Positions absent from the table retain their fixed values. Repeated parameter names impose equality constraints. The rank check on $I-A$ concerns solvability of the equations at the supplied arrays. It does not establish that observed moments identify the parameters.
The names of transforms determine spec$parameters, the order required for the numerical vector passed to ram_expand(). The expansion assigns those names by position; it does not reorder the input using any names the vector already has. A parameter assigned to several locations still occupies only one coordinate. The returned A, S, m and F are the completed arrays at that vector, ready for the moment calculation.
The following constructor places the three marker loadings in $A$ before recording the remaining free loadings and structural coefficients. It can either estimate all nine response intercepts or fix them at supplied means. The option direct = FALSE fixes $c^{\prime}=0$ by leaving its array entry at zero.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
full_sem_spec <- function(means = NULL, direct = TRUE) {
A <- matrix(0, 12, 12)
A[cbind(c(1, 4, 7), 10:12)] <- 1
free_loading_rows <- c(2, 3, 5, 6, 8, 9)
parameter_table <- data.frame(
matrix = c(rep("A", 6), rep("A", 3), rep("S", 12)),
row = c(free_loading_rows, 11, 12, 12, 1:12),
col = c(rep(10:12, each = 2), 10, 11, 10, 1:12),
parameter = c(paste0("loading", free_loading_rows), "a", "b", "cprime",
paste0("residual", 1:9), "phi", "psi1", "psi2"))
if (!direct) {
parameter_table <- parameter_table[parameter_table$parameter != "cprime", ]
}
m <- c(if (is.null(means)) rep(0, 9) else means, 0, 0, 0)
if (is.null(means)) {
parameter_table <- rbind(parameter_table, data.frame(
matrix = "m", row = 1:9, col = 1, parameter = paste0("intercept", 1:9)))
} else {
stopifnot(length(means) == 9, all(is.finite(means)))
}
transforms <- setNames(ifelse(parameter_table$matrix == "S", "log", "identity"),
parameter_table$parameter)
ram_spec(A, diag(12), m, cbind(diag(9), matrix(0, 9, 3)),
parameter_table, transforms)
}
full <- full_sem_spec()
truth <- setNames(c(.8, .7, .9, .75, .85, .65, .6, .5, .2,
rep(.5, 9), 1, .7, .6,
0, .2, -.2, .5, .3, .1, -.1, .4, .2), full$parameters)
print(full$parameter_table)
print(c(free_parameters = length(full$parameters),
observed_variables = nrow(full$F), RAM_variables = full$dimension))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
matrix row col parameter
1 A 2 10 loading2
2 A 3 10 loading3
3 A 5 11 loading5
4 A 6 11 loading6
5 A 8 12 loading8
6 A 9 12 loading9
7 A 11 10 a
8 A 12 11 b
9 A 12 10 cprime
10 S 1 1 residual1
11 S 2 2 residual2
12 S 3 3 residual3
13 S 4 4 residual4
14 S 5 5 residual5
15 S 6 6 residual6
16 S 7 7 residual7
17 S 8 8 residual8
18 S 9 9 residual9
19 S 10 10 phi
20 S 11 11 psi1
21 S 12 12 psi2
22 m 1 1 intercept1
23 m 2 1 intercept2
24 m 3 1 intercept3
25 m 4 1 intercept4
26 m 5 1 intercept5
27 m 6 1 intercept6
28 m 7 1 intercept7
29 m 8 1 intercept8
30 m 9 1 intercept9
free_parameters observed_variables RAM_variables
30 9 12
The parameter table connects the equations to the vector supplied for estimation. The names loading2, loading3, loading5, loading6, loading8 and loading9 refer to the six free entries of $\Lambda$. The names a, b and cprime refer to $a$, $b$ and $c^{\prime}$. Entries residual1 through residual9 are the response error variances $\theta_1,\ldots,\theta_9$. They are distinct from phi, the exogenous factor variance, and psi1 and psi2, the endogenous disturbance variances. Entries intercept1 through intercept9 are $\nu_1,\ldots,\nu_9$. Thus there are six free loadings, three structural coefficients, twelve disturbance variances and nine response intercepts: 30 free parameters.
The vector truth specifies population values for simulation. In particular, $a=0.6$, $b=0.5$, $c^{\prime}=0.2$, $\phi=1$, $\psi_1=0.7$ and $\psi_2=0.6$. The indirect coefficient is $0.3$ and the total coefficient is $0.5$. The value $\psi_1=0.7$ is a variance, not a standard deviation: the standard deviation of $\eta_1$ at a given $\xi$ is $\sqrt{0.7}$. Its marginal variance is $0.6^2(1)+0.7=1.06$. For $\eta_2$, the variance at given values of both predictors is $0.6$, while its marginal variance is $0.5^2(1)+0.5^2(0.7)+0.6=1.025$. These are implications of the supplied population values, not fitted results. The log labels indicate optional variance coordinates; the coordinate maps are defined in Section 7.4. The ordinary fitting calls in Section 7.6 use parameters directly.
The simulation follows the recursive equations in their stated order: first $\xi$, then $\eta_1$, then $\eta_2$. It then forms all nine responses using the measurement equations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(70701)
n <- 500L
xi <- rnorm(n, sd = sqrt(truth["phi"]))
eta1 <- truth["a"] * xi + rnorm(n, sd = sqrt(truth["psi1"]))
eta2 <- truth["cprime"] * xi + truth["b"] * eta1 +
rnorm(n, sd = sqrt(truth["psi2"]))
latent <- cbind(xi, eta1, eta2)
Lambda <- matrix(0, 9, 3)
Lambda[cbind(1:9, rep(1:3, each = 3))] <-
c(1, truth[c("loading2", "loading3")],
1, truth[c("loading5", "loading6")],
1, truth[c("loading8", "loading9")])
Y <- sweep(latent %*% t(Lambda) + matrix(rnorm(n * 9), n, 9) * sqrt(.5),
2, truth[paste0("intercept", 1:9)], "+")
colnames(Y) <- paste0("y", 1:9)
saveRDS(Y, file.path("data/source/ch07", "FULLSEM9.rds"))
saveRDS(list(parameters = truth, latent = latent, seed = 70701L),
file.path("data/source/ch07", "FULLSEM9-truth.rds"))
Each row of latent contains three correlated factor values, despite the independent normal draws used for their disturbances. For example, response four is its intercept plus $\eta_1$ and an independent response error of variance $0.5$. Response five instead multiplies $\eta_1$ by its free loading. Only Y is supplied for estimation. The separate truth file is for checking recovery; it is not an additional source of observed predictors.
An observed-variable path model
A smaller example clarifies the distinction between structural intercepts and marginal means. Suppose all three variables are observed and
\[y_1=1+\varepsilon_1,\qquad y_2=0.2+0.6y_1+\varepsilon_2,\qquad y_3=-0.1+0.4y_1+\varepsilon_3,\]with mutually independent centered normal disturbances having variances $1$, $0.5$ and $0.7$. There is no measurement layer: $F=I_3$. The coefficient $0.6$ is the change in $E(y_2\mid y_1)$ per unit of $y_1$, and $0.4$ is the change in $E(y_3\mid y_1)$ per unit of $y_1$. Their units are those of their respective outcomes per unit of the predictor. The intercept $0.2$ in the second equation is the expected value of $y_2$ at $y_1=0$. Its marginal mean also includes the contribution of $E(y_1)=1$.
The variance $1$ describes the marginal variation in the exogenous observed variable $y_1$. The variances $0.5$ and $0.7$ describe variation in $y_2$ and $y_3$ around their respective regressions on $y_1$, in squared outcome units. Their marginal variances also include the contributions $0.6^2\operatorname{Var}(y_1)$ and $0.4^2\operatorname{Var}(y_1)$. In a path model without a separate measurement layer, these disturbances include whatever outcome variation the specified regressions leave unexplained.
1
2
3
4
5
6
7
8
9
10
11
12
13
path_spec <- function() {
parameter_table <- data.frame(matrix = c("A", "A", rep("S", 3), rep("m", 3)),
row = c(2, 3, 1:3, 1:3), col = c(1, 1, 1:3, rep(1, 3)),
parameter = c("a21", "a31", paste0("variance", 1:3), paste0("intercept", 1:3)))
ram_spec(matrix(0, 3, 3), diag(3), rep(0, 3), diag(3), parameter_table,
setNames(c(rep("identity", 2), rep("log", 3), rep("identity", 3)), parameter_table$parameter))
}
path <- path_spec()
theta_path <- c(.6, .4, 1, .5, .7, 1, .2, -.1)
equal_path <- path
equal_path$parameter_table$parameter[2] <- "a21"
equal_path$parameters <- equal_path$parameters[-2]
equal_path$transforms <- equal_path$transforms[-2]
The vector theta_path follows the parameter table’s order: two path coefficients, three disturbance variances and three structural intercepts. Its last three entries are the intercepts in the equations, rather than the three marginal means. The repeated name a21 in equal_path assigns one coefficient to both outgoing paths from $y_1$. Deleting the second coordinate reduces the free parameter count from eight to seven. The lavaan package specifies these measurement and structural equations in its model syntax.
7.2 Model-implied means and covariances
When $I-A$ is invertible, solving the structural equations gives $v=(I-A)^{-1}(m+\varepsilon)$. Write $B=(I-A)^{-1}$ and $C=FB$. In this chapter $B$ denotes this inverse system matrix, not the matrix of direct structural coefficients. Since $E(\varepsilon)=0$, the observed moments are
\[\mu=Cm,\qquad \Sigma=CSC^\top.\]The inverse includes transmission along every allowed path. In the recursive model above, for instance, its entry taking $\xi$’s disturbance to $\eta_2$ is $c^{\prime}+ab$. ram_implied() expands the parameters, solves the equations, selects the observed rows, and evaluates these two moments. The separate function ram_admissibility() inspects the disturbance covariance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ram_implied <- function(theta, spec) {
model <- ram_expand(theta, spec)
system <- diag(spec$dimension) - model$A
if (qr(system)$rank < spec$dimension) stop("I - A is not invertible.")
B <- solve(system)
C <- model$F %*% B
mu <- drop(C %*% model$m)
Sigma <- C %*% model$S %*% t(C)
if (any(!is.finite(c(mu, Sigma)))) stop("Nonfinite implied moments")
chol(Sigma)
c(model, list(B = B, C = C, mean = mu, covariance = Sigma))
}
ram_admissibility <- function(theta, spec) {
S <- ram_expand(theta, spec)$S
list(negative_variances = which(diag(S) < 0),
smallest_disturbance_eigenvalue = min(eigen(S, symmetric = TRUE, only.values = TRUE)$values))
}
The Cholesky factorization in ram_implied() requires a positive definite response covariance. It does not require $S$ to be positive semidefinite. This distinction matters because some improper disturbance variances can still produce a positive definite $\Sigma$. The admissibility check therefore reports both negative diagonal entries of $S$ and its smallest eigenvalue.
In this specification, the returned B is $12\times12$ and C is $9\times12$. The fields mean and covariance contain the nine response means and their $9\times9$ covariance, in the order selected by $F$. The result also retains the expanded arrays. Later derivative calculations use B, C, S and m, whereas the likelihood uses only the observed mean and covariance. negative_variances contains positions in the diagonal of $S$, rather than the variance values themselves.
For the full SEM, let $t=c^{\prime}+ab$. Independence of $\xi,\zeta_1,\zeta_2$ gives
\[V_f=\operatorname{Var}(f)= \begin{pmatrix} \phi&a\phi&t\phi\\ a\phi&a^2\phi+\psi_1&at\phi+b\psi_1\\ t\phi&at\phi+b\psi_1&t^2\phi+b^2\psi_1+\psi_2 \end{pmatrix}.\]For example, $\operatorname{Cov}(\eta_1,\eta_2)$ has one contribution $at\phi$ from $\xi$ and another $b\psi_1$ from the disturbance of $\eta_1$, which also enters $\eta_2$. The response covariance must consequently equal $\Lambda V_f\Lambda^\top+\Theta$. This is the familiar measurement-model expression, now with its factor covariance determined by structural coefficients and disturbance variances.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
full_moments <- ram_implied(truth, full)
a <- unname(truth["a"])
b <- unname(truth["b"])
cprime <- unname(truth["cprime"])
phi <- unname(truth["phi"])
psi1 <- unname(truth["psi1"])
psi2 <- unname(truth["psi2"])
total <- cprime + a * b
V_latent <- matrix(c(
phi, a * phi, total * phi,
a * phi, a^2 * phi + psi1, a * total * phi + b * psi1,
total * phi, a * total * phi + b * psi1,
total^2 * phi + b^2 * psi1 + psi2), 3, 3)
print(V_latent)
print(c(covariance_gap = max(abs(full_moments$covariance -
Lambda %*% V_latent %*% t(Lambda) - diag(.5, 9))),
mean_gap = max(abs(full_moments$mean - truth[paste0("intercept", 1:9)]))))
record_check("full_SEM_moment_identity", max(abs(full_moments$covariance -
Lambda %*% V_latent %*% t(Lambda) - diag(.5, 9))), 1e-12)
1
2
3
4
5
6
[,1] [,2] [,3]
[1,] 1.0 0.60 0.500
[2,] 0.6 1.06 0.650
[3,] 0.5 0.65 1.025
covariance_gap mean_gap
2.220446e-16 0.000000e+00
The two covariance calculations differ by at most $2.22\times10^{-16}$, consistent with numerical rounding. Their agreement checks the RAM assignments against the reduced equations; it does not require the sample covariance to equal the population covariance. At the specified parameters, $\operatorname{Var}(\eta_1)=1.06$, $\operatorname{Var}(\eta_2)=1.025$, and $\operatorname{Cov}(\eta_1,\eta_2)=0.65$, as the displayed latent covariance confirms.
The path example has $E(y)=(1,0.8,0.3)^\top$. Its covariance between $y_2$ and $y_3$ is $0.6\times0.4\times\operatorname{Var}(y_1)=0.24$, even though their disturbances are independent. Under the common coefficient $0.6$, that covariance becomes $0.36$.
1
2
3
print(ram_implied(theta_path, path)$mean)
print(ram_implied(theta_path, path)$covariance)
print(ram_implied(theta_path[-2], equal_path)$covariance)
1
2
3
4
5
6
7
8
9
[1] 1.0 0.8 0.3
[,1] [,2] [,3]
[1,] 1.0 0.60 0.40
[2,] 0.6 0.86 0.24
[3,] 0.4 0.24 0.86
[,1] [,2] [,3]
[1,] 1.0 0.60 0.60
[2,] 0.6 0.86 0.36
[3,] 0.6 0.36 1.06
The printed mean and covariance matrices agree with these calculations, including the larger covariance between the second and third variables under the common coefficient.
A latent growth model for repeated responses
Now suppose the same response is measured at times $t=0,1,2,3$ for each person. A latent growth model gives each person an intercept $I_i$ and a slope $L_i$:
\[y_{it}=I_i+tL_i+e_{it},\qquad \begin{pmatrix}I_i\\L_i\end{pmatrix} =\begin{pmatrix}\beta_0\\\beta_1\end{pmatrix} +\begin{pmatrix}b_{0i}\\b_{1i}\end{pmatrix},\qquad \begin{pmatrix}b_{0i}\\b_{1i}\end{pmatrix}\sim N(0,G), \quad G=\begin{pmatrix}g_{00}&g_{01}\\g_{01}&g_{11}\end{pmatrix}.\]The errors $e_{it}$ are independent of the growth factors, independent across occasions, and normal with mean zero. People are independent. The specification initially allows a different error variance $\theta_t$ at each occasion; the main fit then imposes a common variance $\psi$. These assumptions describe a joint model for a person’s four responses; four observations from one person are not four independent sampling units.
The latent intercept $I_i$ is the person’s expected response at time zero. It differs from the observed baseline response by $e_{i0}$. The latent slope $L_i$ is the person’s expected change per unit of the recorded time scale. Its population mean $\beta_1$ describes average linear change, while $g_{11}$ describes between-person variation in slopes. Similarly, $\beta_0$ is the population mean of the latent intercepts and $g_{00}$ their variance. A positive $g_{01}$ associates higher starting levels with more positive slopes. This association concerns variation among people, not the direction of change within a single person.
This is a latent-variable model even though its loadings are fixed. Every occasion loads one unit on $I_i$ and $t$ units on $L_i$. Those known coefficients encode the linear trajectory. With
\[Z=\begin{pmatrix}1&0\\1&1\\1&2\\1&3\end{pmatrix},\qquad \beta=\begin{pmatrix}\beta_0\\\beta_1\end{pmatrix},\]the four responses satisfy $y_i=Z\beta+Zb_i+e_i$. Their mean and covariance are
\[\mu=Z\beta,\qquad \Sigma=ZGZ^\top+\operatorname{diag}(\theta_0,\theta_1,\theta_2,\theta_3).\]Entry by entry, these equations give
\[E(y_{it})=\beta_0+t\beta_1,\qquad \operatorname{Cov}(y_{it},y_{iu})=g_{00}+(t+u)g_{01}+tu\,g_{11} +\mathbf{1}_{\{t=u\}}\theta_t.\]Thus independent occasion errors do not make the responses independent. Two responses share the person’s latent intercept and slope. The error variance affects only a diagonal entry, while changing $g_{11}$ affects every covariance involving two nonzero times. At $t=0$ the slope contributes nothing to the response itself, but $g_{01}$ still affects its covariance with a later response.
The time origin changes parameter interpretations. If $t^\ast =t-c$, then $I_i^\ast =I_i+cL_i$ and $L_i^\ast =L_i$. Consequently $\beta_0^\ast =\beta_0+c\beta_1$, $g_{00}^\ast =g_{00}+2cg_{01}+c^2g_{11}$, and $g_{01}^\ast =g_{01}+cg_{11}$. A change in intercept-slope correlation after recentering time need not represent any change in fitted trajectories. A different time unit also rescales slopes and their variances.
For the RAM representation order the variables as $(y_{i0},y_{i1},y_{i2},y_{i3},I_i,L_i)$. The final two columns of the observed rows of $A$ are $Z$. The final block of $S$ is $G$, and its first four diagonal entries contain the occasion error variances. The observed entries of $m$ are fixed at zero; the final two entries are $\beta_0,\beta_1$.
The zero observed intercepts locate the growth-factor means and restrict the four expected responses to a line. If all four observed intercepts and both latent means were free, adding a constant to the latent intercept mean and subtracting it from every observed intercept would leave the mean vector unchanged. A similar tradeoff exists for the slope mean and occasion intercepts proportional to time. Fixing all four observed intercepts at zero removes those two indeterminacies and imposes two further restrictions on the four response means. Thus this choice does more than identify the latent means: it specifies the linear population trajectory. There is no need also to fix a growth-factor variance at one, because the fixed loading patterns already define their scales.
The constructor below implements these assignments. Its nine stored parameters are four occasion error variances, three entries of $G$, and two latent means.
1
2
3
4
5
6
7
8
9
10
growth_spec <- function() {
A <- matrix(0, 6, 6)
A[1:4, 5:6] <- cbind(1, 0:3)
parameter_table <- data.frame(matrix = c(rep("S", 7), "m", "m"),
row = c(1:4, 5, 6, 6, 5, 6), col = c(1:4, 5, 5, 6, 1, 1),
parameter = c(paste0("residual", 1:4), "G11", "G21", "G22", "mean_intercept", "mean_slope"))
transforms <- setNames(rep("identity", 9), parameter_table$parameter)
ram_spec(A, diag(6), rep(0, 6), cbind(diag(4), matrix(0, 4, 2)), parameter_table, transforms)
}
growth <- growth_spec()
In the returned specification, G11, G21 and G22 denote $g_{00}$, $g_{01}$ and $g_{11}$. The code names use the two rows of $G$, while the mathematical subscripts refer to intercept and slope. The covariance G21 is recorded at $S_{6,5}$ and expanded symmetrically. The two means occupy entries five and six of $m$, so they produce the four observed means through the fixed loadings.
The main fit will require equal occasion error variances. A linear map $\theta=Kz$ represents the nine stored entries using six free coordinates: one common error variance, three entries of $G$ and two means. The following population illustration constructs that map along with the specified moments.
1
2
3
4
5
6
7
8
9
10
Z_time <- cbind(1, 0:3)
G <- matrix(c(1, .15, .15, .25), 2)
theta_growth <- c(rep(.49, 4), 1, .15, .25, 2, .4)
growth_K <- rbind(cbind(rep(.5, 4), matrix(0, 4, 5)), cbind(0, diag(5)))
stopifnot(max(abs(crossprod(growth_K) - diag(6))) < 1e-12)
growth_moments <- ram_implied(theta_growth, growth)
print(growth_moments$mean)
print(growth_moments$covariance)
record_check("growth_moment_identity", max(abs(growth_moments$covariance -
Z_time %*% G %*% t(Z_time) - diag(.49, 4))), 1e-12)
1
2
3
4
5
6
[1] 2.0 2.4 2.8 3.2
[,1] [,2] [,3] [,4]
[1,] 1.49 1.15 1.30 1.45
[2,] 1.15 2.04 1.95 2.35
[3,] 1.30 1.95 3.09 3.25
[4,] 1.45 2.35 3.25 4.64
The $9\times6$ matrix growth_K has orthonormal columns, as the cross-product check confirms. Its first column has four entries equal to $1/2$, so the first free coordinate is $z_1=2\psi$ and each stored error variance is $\psi$. The remaining five coordinates are unchanged. At the supplied error variance $0.49$, $z_1=0.98$. This linear restriction does not itself constrain $G$ to be positive semidefinite or the common error variance to be positive; those conditions require separate checking.
The population illustration uses $\beta_0=2$, $\beta_1=0.4$, $g_{00}=1$, $g_{01}=0.15$, $g_{11}=0.25$, and $\psi=0.49$. The means are therefore $2,2.4,2.8,3.2$. Baseline response variance is $1.49$, the covariance between times zero and one is $1.15$, and response variance at time three is $4.64$. These values illustrate the mean and covariance equations independently of the sample used for fitting.
The existing GROWTH4 example contains 200 simulated people observed at these four times. Its wide form has one row per person. Its long form repeats each person’s identifier over four rows. Reading both permits a check of the correspondence without regenerating or changing the shared data.
1
2
3
4
5
6
7
8
growth_input <- readRDS(file.path("data/source/ch07/GROWTH4.rds"))
wide <- growth_input$wide
long <- growth_input$long
stopifnot(identical(dim(wide), c(200L, 4L)))
record_check("growth_wide_long", max(abs(matrix(long$response, nrow(wide),
byrow = TRUE) - wide)), 1e-12)
saveRDS(growth_input, file.path("data/source/ch07", "GROWTH4.rds"))
print(c(people = nrow(wide), occasions = ncol(wide), long_rows = nrow(long)))
1
2
people occasions long_rows
200 4 800
The model has 14 observable moments: four means and ten distinct covariance entries. Four separate error variances would give nine free parameters and, at full local rank, five degrees of freedom. The common error variance reduces the count to six and raises the degrees of freedom to eight. Counting moments is necessary but does not prove identification. The lavaan function lavInspect() returns the model-implied means and covariances of a fitted model.
7.3 Maximum likelihood, generalized least squares, and unweighted least squares
The full SEM predicts nine response means and 45 distinct variances and covariances. To assess their discrepancy from the data, let $y_i$ contain the $p$ responses of person $i$, $\bar y$ their sample mean, and $S_n$ their sample covariance with divisor $n$. Under the normal model $y_i\sim N(\mu,\Sigma)$. Write $P=\Sigma^{-1}$ and $r=\bar y-\mu$. Decomposing $y_i-\mu=(y_i-\bar y)+r$ removes the cross terms when summed over people and gives
\[\sum_{i=1}^n(y_i-\mu)^\top P(y_i-\mu) =n\operatorname{tr}(P S_n)+n r^\top P r.\]The full normal negative log likelihood, including its normalizing constant, is therefore
\[f_{\rm ML}(\mu,\Sigma)=\frac n2\left\{p\log(2\pi)+\log|\Sigma| +\operatorname{tr}(P S_n)+r^\top P r\right\}.\]The last term measures the cost of a mean restriction. If $r$ lies along a covariance eigenvector with eigenvalue $\lambda$, then $r^\top P r=\Vert r\Vert^2/\lambda$: a given mean discrepancy costs more in a direction with smaller variance. In the full SEM, free response intercepts can reproduce all nine sample means. In the growth model only two means determine the entire four-occasion trajectory, so that term generally remains positive after fitting.
For covariance-only fitting, generalized least squares (GLS) and unweighted least squares (ULS) compare individual variances and covariances. Here both use $S_1=nS_n/(n-1)$, the unbiased sample covariance, and the multiplier $c=(n-1)/n$. With $E=S_1-\Sigma$ and $W=S_1^{-1}$, the implemented criteria are
\[\mathcal F_{\rm GLS}=\frac c4\operatorname{tr}(WEWE),\qquad \mathcal F_{\rm ULS}=\frac c2\sum_{j\geq k}E_{jk}^2.\]GLS uses a positive definite sample covariance to construct its weight. ULS gives equal weight to each distinct covariance entry in the original response units, so a change of measurement units changes the relative contribution of those discrepancies. A whole-matrix sum of squares would count every off-diagonal discrepancy twice; the lower-triangle sum above counts it once. The multiplier $c$ changes the criterion’s scale but not its minimizer within a given sample.
The function sem_data() obtains the sample moments through fa_data(). Summary-matrix input must include the sample size, divisor and mean vector. This implementation requires a positive definite sample covariance even for ULS, although the ULS formula itself does not require an inverse. ram_criterion() evaluates the requested function at supplied model moments.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
sem_data <- function(Y = NULL, covariance = NULL, mean = NULL, n = NULL, divisor = NULL) {
data <- fa_data(Y, covariance, n, divisor)
if (is.null(Y)) {
stopifnot(length(mean) == data$p, all(is.finite(mean)))
data$mean <- mean
}
data
}
ram_criterion <- function(mu, Sigma, data, estimator = "ML") {
stopifnot(estimator %in% c("ML", "GLS", "ULS"))
if (estimator == "ML") {
R <- chol(Sigma)
K <- chol2inv(R)
r <- data$mean - mu
return(data$n / 2 * (data$p * log(2 * pi) + 2 * sum(log(diag(R))) +
sum(K * data$S) + drop(crossprod(r, K %*% r))))
}
# GLS and ULS use the unbiased covariance S1 = S n / (n - 1) and the multiplier (n - 1) / n.
S1 <- data$S * data$n / (data$n - 1)
E <- S1 - Sigma
if (estimator == "GLS") {
W <- chol2inv(chol(S1))
return((data$n - 1) / data$n * sum(diag((W %*% E) %*% (W %*% E))) / 4)
}
(data$n - 1) / data$n * sum(E[lower.tri(E, diag = TRUE)]^2) / 2
}
The data object stores S with divisor $n$, including when summary input originally uses divisor $n-1$. Its mean, p and n describe the same response order and sample. In the maximum likelihood (ML) branch, R is an upper Cholesky factor of $\Sigma$ and K is its inverse covariance $P$. Thus 2 * sum(log(diag(R))) supplies the log determinant, sum(K * data$S) supplies the trace, and crossprod(r, K %*% r) supplies the mean penalty. The GLS and ULS branches first recover $S_1$ from data$S. Each branch returns one criterion value, not parameter estimates; the ML value is a full-sample negative log likelihood, whereas the two least squares values use the scaled criteria above.
For the next comparison, fix the nine response intercepts at the sample means. The two rows then differ only in their covariance parameters. The generating row uses the population covariance parameters; the displaced row uses smaller structural coefficients and larger response-error variances. Neither row is an optimized fit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
full_data <- sem_data(Y)
cov_spec <- full_sem_spec(means = full_data$mean)
cov_truth <- truth[cov_spec$parameters]
displaced <- cov_truth
displaced[c("a", "b", "cprime")] <- c(.3, .2, 0)
displaced[paste0("residual", 1:9)] <- .7
criterion_table <- do.call(rbind, lapply(list(generating_covariance = cov_truth,
displaced_covariance = displaced), function(theta) {
moments <- ram_implied(theta, cov_spec)
vapply(c("ML", "GLS", "ULS"), function(method) {
ram_criterion(moments$mean, moments$covariance, full_data, method)
}, 0.0)
}))
print(criterion_table)
1
2
3
ML GLS ULS
generating_covariance 5920.511 0.03562308 0.05509361
displaced_covariance 6084.705 0.51893495 1.71980592
Every criterion assigns a smaller value to the generating covariance than to the displaced covariance. For ML, for example, the negative log likelihood rises from $5920.511$ to $6084.705$. This comparison concerns two specified points, so it does not establish that the generating parameters minimize the sample criterion.
The numerical scales of ML, GLS and ULS are different. A criterion can rank parameter vectors within its own column, but subtracting an ML value from a ULS value has no likelihood interpretation. The fixed means are essential for GLS and ULS: these covariance criteria contain no information from which to estimate free mean parameters. The lavaan package provides ML, GLS and ULS estimation through its estimator argument.
7.4 Partial derivatives of the RAM matrices and the fitting function
Changing $b$ alters the propagation of $\eta_1$ into $\eta_2$, and therefore many response covariances at once. The derivative starts with a one at $A_{12,11}$, its position in the structural equations. For a general free parameter $\theta_j$, the derivatives of $A,S,m$ contain ones at its recorded assignments and zeros elsewhere. A covariance contributes to both symmetric positions of $S$. A shared parameter contributes at every location using its name.
Differentiating $(I-A)B=I$ gives $-(dA)B+(I-A)dB=0$, hence $dB=B(dA)B$ and $dC=C(dA)B$. Applying the product rule yields
\[\begin{aligned} d\mu&=(dC)m+C\,dm,\\ d\Sigma&=(dC)SC^\top+CS(dC)^\top+C(dS)C^\top. \end{aligned}\]The routine below constructs each parameter’s array derivatives and propagates them through these expressions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
ram_derivatives <- function(theta, spec) {
model <- ram_implied(theta, spec)
p <- nrow(spec$F)
k <- length(theta)
dmu <- matrix(0, p, k, dimnames = list(NULL, spec$parameters))
dSigma <- array(0, c(p, p, k), dimnames = list(NULL, NULL, spec$parameters))
for (j in seq_len(k)) {
dA <- dS <- matrix(0, spec$dimension, spec$dimension)
dm <- numeric(spec$dimension)
positions <- spec$parameter_table[spec$parameter_table$parameter == spec$parameters[j], , drop = FALSE]
for (r in seq_len(nrow(positions))) {
pos <- positions[r, ]
if (pos$matrix == "A") dA[pos$row, pos$col] <- 1
if (pos$matrix == "m") dm[pos$row] <- 1
if (pos$matrix == "S") dS[pos$row, pos$col] <- dS[pos$col, pos$row] <- 1
}
dC <- model$C %*% dA %*% model$B
dmu[, j] <- drop(dC %*% model$m + model$C %*% dm)
change <- dC %*% model$S %*% t(model$C)
dSigma[, , j] <- change + t(change) + model$C %*% dS %*% t(model$C)
}
list(mean = dmu, covariance = dSigma, model = model)
}
In ram_derivatives(), change is the covariance change through the left copy of $C$. Its transpose is the change through the right copy. The final term allows the disturbance covariance itself to change. Column $j$ of the returned mean derivative and slice $j$ of its covariance derivative correspond to the same parameter.
For this model, mean has dimensions $9\times30$ and covariance has dimensions $9\times9\times30$, with the final index in full$parameters order. These are derivatives at the supplied vector, rather than new implied moments. The field model contains those moments and the expanded RAM arrays. For b, the assignment loop places one at dA[12, 11]; for a shared coefficient, it places a one at every assigned path before propagating the change.
For $b$ the reduced-equation formulas provide simple checks:
\[\frac{\partial\operatorname{Cov}(\xi,\eta_2)}{\partial b}=a\phi,\qquad \frac{\partial\operatorname{Cov}(\eta_1,\eta_2)}{\partial b}=a^2\phi+\psi_1,\qquad \frac{\partial\operatorname{Var}(\eta_2)}{\partial b} =2a(c'+ab)\phi+2b\psi_1.\]Because the marker loadings equal one, these are also the derivatives of $\Sigma_{1,7}$, $\Sigma_{4,7}$ and $\Sigma_{7,7}$. At the generating values they are $0.6$, $1.06$ and $1.3$. All factor means are zero, so this structural coefficient changes no response mean in the present parameterization.
To differentiate the likelihood with respect to these moments, use $dP=-P(d\Sigma)P$. The log determinant contributes $\operatorname{tr}(P\,d\Sigma)$, while the sample-covariance and mean-residual terms contribute negative precision-weighted quadratic terms. In
\[df_{\rm ML}=\operatorname{tr}(Q^\top d\Sigma)+q^\top d\mu,\]the resulting sensitivities are
\[Q=\frac n2\left(P-P S_nP-Prr^\top P\right),\qquad q=-nPr.\]For GLS, with $D=\Sigma-S_1$, differentiation gives $Q=cWDW/2$. For ULS the diagonal entries are $cD_{jj}$ and the off-diagonal entries are $cD_{jk}/2$. Summing over the whole symmetric matrix then counts each distinct covariance once. Both least squares criteria have $q=0$.
Working coordinates and the gradient of the criterion
The calculations so far use original parameters. Optional working coordinates can enforce positive scalar variances. The following functions map those coordinates into the parameters and pack the parameters back into coordinates. ram_identity() provides the alternative that uses parameters directly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ram_map <- function(u, spec) {
stopifnot(length(u) == length(spec$parameters), all(is.finite(u)))
theta <- u
derivative <- rep(1, length(u))
positive <- spec$transforms == "log"
correlation <- spec$transforms == "tanh"
theta[positive] <- log_to_positive(u[positive])
derivative[positive] <- theta[positive]
theta[correlation] <- tanh(u[correlation])
if (any(abs(theta[correlation]) >= 1)) stop("Correlation at a rounded boundary")
derivative[correlation] <- 1 - theta[correlation]^2
list(theta = setNames(theta, spec$parameters), jacobian = diag(derivative, length(u)))
}
ram_pack <- function(theta, spec) {
u <- theta
u[spec$transforms == "log"] <- positive_to_log(theta[spec$transforms == "log"])
rho <- theta[spec$transforms == "tanh"]
stopifnot(all(abs(rho) < 1))
u[spec$transforms == "tanh"] <- atanh(rho)
setNames(u, spec$parameters)
}
ram_identity <- function(spec) {
function(u) list(theta = setNames(u, spec$parameters), jacobian = diag(length(u)))
}
For the full SEM, ram_pack() takes logarithms of the twelve variances and leaves the loadings, structural coefficients and intercepts unchanged. ram_map() exponentiates those variance coordinates and returns the diagonal Jacobian $J=\partial\theta/\partial u^\top$. The positive-variance map makes the diagonal $S$ positive definite in this particular specification. Marker loadings are fixed and require no sign transformation.
The generic tanh option applies to a parameter restricted to $(-1,1)$, such as a correlation. A covariance between variables with variances $v_1$ and $v_2$ instead has absolute bound $\sqrt{v_1v_2}$. With both variances fixed at one, that covariance is also the correlation. The full SEM uses no such coordinate. At finite coordinates the hyperbolic tangent represents strict inequalities in exact arithmetic; the implementation rejects a value rounded to either endpoint. Neither the elementwise log map nor this correlation map is a general parameterization for a covariance block such as the growth model’s $G$.
The next two functions evaluate the moment sensitivities and combine them with the parameter derivatives. Their returned objective uses the chain rule $\nabla_u f=J^\top\nabla_\theta f$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ram_sensitivity <- function(mu, Sigma, data, estimator) {
if (estimator == "ML") {
K <- chol2inv(chol(Sigma))
r <- data$mean - mu
kr <- drop(K %*% r)
return(list(covariance = data$n / 2 * (K - K %*% data$S %*% K - tcrossprod(kr)),
mean = -data$n * kr))
}
S1 <- data$S * data$n / (data$n - 1)
weight <- (data$n - 1) / data$n
if (estimator == "GLS") {
W <- chol2inv(chol(S1))
Q <- weight / 2 * W %*% (Sigma - S1) %*% W
} else {
Q <- weight * (Sigma - S1)
Q[row(Q) != col(Q)] <- Q[row(Q) != col(Q)] / 2
}
list(covariance = Q, mean = rep(0, data$p))
}
The returned covariance and mean are the sensitivity matrix $Q$ and vector $q$. For ML, kr is $Pr$, so tcrossprod(kr) forms $Prr^\top P$. These sensitivities describe changes in the criterion per change in an observed moment. They become parameter derivatives only after combination with the derivatives returned by ram_derivatives().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
make_ram_objective <- function(spec, data, estimator = "ML", map = function(u) ram_map(u, spec)) {
stopifnot(estimator %in% c("ML", "GLS", "ULS"))
evaluate <- function(u, derivatives = TRUE) {
mapped <- map(u)
model <- ram_implied(mapped$theta, spec)
if (estimator != "ML" && max(abs(model$mean - data$mean)) > 1e-12) stop("GLS/ULS require saturated fixed means")
value <- ram_criterion(model$mean, model$covariance, data, estimator)
gradient <- NULL
if (derivatives) {
D <- ram_derivatives(mapped$theta, spec)
if (estimator != "ML" && any(abs(D$mean) > 1e-12)) stop("GLS/ULS do not estimate mean parameters")
Q <- ram_sensitivity(model$mean, model$covariance, data, estimator)
original <- vapply(seq_along(u), function(j) sum(Q$covariance * D$covariance[, , j]) +
sum(Q$mean * D$mean[, j]), 0.0)
gradient <- drop(crossprod(mapped$jacobian, original))
}
list(value = value, gradient = gradient, model = model, mapped = mapped)
}
list(fn = function(u) tryCatch(evaluate(u, FALSE)$value, error = function(e) Inf),
gr = function(u) evaluate(u)$gradient, evaluate = evaluate, data = data,
spec = spec, map = map, estimator = estimator)
}
Inside make_ram_objective(), Q is the list of those two sensitivities. For parameter $j$, the sum of Q$covariance * D$covariance[, , j] evaluates the trace in the differential, and the mean-product sum evaluates $q^\top\dot\mu_j$. Their sum is original[j], the derivative with respect to the original parameter. Multiplication by the transpose of mapped$jacobian then gives the working-coordinate gradient. For example, at $\psi_1=0.7$, the derivative with respect to $\log\psi_1$ is $0.7$ times the derivative with respect to $\psi_1$. The derivative with respect to b is unchanged because that coordinate uses the identity map.
The two least squares checks address different requirements. A model mean can equal the sample mean at one supplied vector even though a free parameter could change it. The first check requires equality at the current point; the check on D$mean additionally rejects a parameterization with nonzero mean derivatives there. The specification cov_spec satisfies both by fixing the observed intercepts at sample means and fixing latent means at zero.
The returned fn, gr and evaluate use the same stored specification and data. fn evaluates only the criterion; gr returns a gradient in its input coordinates; and evaluate returns both, with the mapped parameters and implied moments. Its default uses transformed coordinates. Passing ram_identity(full) instead makes its input an original-scale vector. The error handler belongs to fn: an invalid value evaluation returns infinity so a search can reject that trial, while a failed derivative evaluation remains an error. Neither behavior establishes disturbance admissibility.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
u_truth <- ram_pack(truth, full)
objective_transformed <- make_ram_objective(full, full_data)
objective_natural <- make_ram_objective(full, full_data, map = ram_identity(full))
gradient_gap <- max(abs(objective_transformed$gr(u_truth) -
num_grad(objective_transformed$fn, u_truth)$gradient))
D <- ram_derivatives(truth, full)
b_column <- match("b", full$parameters)
print(c(transformed_gradient_gap = gradient_gap,
derivative_y1_y7_b = D$covariance[1, 7, b_column],
derivative_y4_y7_b = D$covariance[4, 7, b_column],
derivative_y7_variance_b = D$covariance[7, 7, b_column]))
record_check("full_SEM_gradient", gradient_gap, 2e-5)
shared_D <- ram_derivatives(theta_path[-2], equal_path)
print(c(shared_slope_covariance_derivative = shared_D$covariance[2, 3, 1]))
record_check("shared_path_derivative", abs(shared_D$covariance[2, 3, 1] - 1.2), 1e-12)
1
2
3
4
transformed_gradient_gap derivative_y1_y7_b.b derivative_y4_y7_b.b derivative_y7_variance_b.b
5.235586e-07 6.000000e-01 1.060000e+00 1.300000e+00
shared_slope_covariance_derivative.a21
1.2
The numerical gradient perturbs the same working coordinates supplied to the analytic gradient. Their largest absolute difference is $5.24\times10^{-7}$ at this parameter vector, and the three displayed covariance derivatives reproduce $0.6$, $1.06$ and $1.3$. Comparing derivatives on different scales would create an artificial discrepancy. The separate shared-path check gives $\partial\operatorname{Cov}(y_2,y_3)/\partial a_{21}=2a_{21}\operatorname{Var}(y_1)=1.2$: both occurrences of the coefficient must be differentiated. It checks the handling of equality constraints, rather than only a parameter appearing in one array position. The numDeriv package provides numerical derivatives for checking such analytic expressions.
7.5 Expected information, identification, and standard errors
Moment derivatives describe which parameter changes the observed distribution can distinguish. Let $x=y-\mu$, $P=\Sigma^{-1}$, and let $\mu_a,\Sigma_a$ denote derivatives with respect to $\theta_a$. One person’s likelihood score component is
\[s_a=\mu_a^\top Px+\frac12\left\{x^\top P\Sigma_aPx-\operatorname{tr}(P\Sigma_a)\right\}.\]The first term is linear in a centered normal response and the second is a centered quadratic form. Their covariance vanishes because centered normal third moments are zero. For symmetric matrices $H_a,H_b$, the normal fourth-moment identity gives $\operatorname{Cov}(x^\top H_a x,x^\top H_bx)=2\operatorname{tr}(H_a\Sigma H_b\Sigma)$. Substituting $H_a=P\Sigma_aP$ and multiplying the one-person information by the number of independent people yields
\[I_{ab}=\frac n2\operatorname{tr}(P\Sigma_aP\Sigma_b)+n\mu_a^\top P\mu_b.\]An observed intercept in the full SEM changes one mean at rate one and leaves all covariances fixed, so its diagonal information is $nP_{jj}$. A structural coefficient instead contributes through the covariance derivatives in this zero-factor-mean model. Under a parameter map with Jacobian $J$, information in working coordinates is $I_u=J^\top I_\theta J$.
The following functions compute expected information and inspect the rank of the derivatives of the distinct observable moments.
1
2
3
4
5
6
7
8
9
10
11
ram_information <- function(theta, spec, n, jacobian = diag(length(theta))) {
D <- ram_derivatives(theta, spec)
K <- chol2inv(chol(D$model$covariance))
k <- length(theta)
information <- matrix(0, k, k)
for (a in seq_len(k)) for (b in seq_len(a)) {
information[a, b] <- information[b, a] <- n / 2 * sum(diag(K %*% D$covariance[, , a] %*%
K %*% D$covariance[, , b])) + n * sum(D$mean[, a] * drop(K %*% D$mean[, b]))
}
crossprod(jacobian, information %*% jacobian)
}
The loop constructs each symmetric entry of the information from the covariance trace and mean-derivative product. The multiplier n already makes this full-sample information. With the identity jacobian, the return value is a $30\times30$ matrix for the full SEM’s original parameters. A supplied Jacobian transforms that matrix into the corresponding working coordinates. For the growth restriction it is growth_K, giving a $6\times6$ information matrix even though nine entries are stored in the parameter vector.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ram_identification <- function(theta, spec, n, jacobian = diag(length(theta)), tolerance = 1e-8) {
D <- ram_derivatives(theta, spec)
lower <- lower.tri(D$model$covariance, diag = TRUE)
J <- rbind(D$mean, vapply(seq_along(theta), function(j) D$covariance[, , j][lower], numeric(sum(lower)))) %*% jacobian
singular <- svd(J, nu = 0, nv = 0)$d
rank <- sum(singular > tolerance * max(singular))
information <- ram_information(theta, spec, n, jacobian)
eigenvalues <- eigen(information, symmetric = TRUE, only.values = TRUE)$values
valid <- rank == ncol(jacobian) && min(eigenvalues) > tolerance * max(eigenvalues)
working_covariance <- if (valid) chol2inv(chol(information)) else NULL
covariance <- if (valid) jacobian %*% working_covariance %*% t(jacobian) else NULL
list(moment_jacobian = J, rank = rank, information = information, eigenvalues = eigenvalues,
covariance = covariance, working_covariance = working_covariance,
se = if (valid) sqrt(diag(covariance)) else rep(NA_real_, length(theta)),
valid = valid, reason = if (valid) "full_local_rank" else "singular_or_weak_information")
}
The moment Jacobian stacks the mean derivatives above the lower-triangle covariance derivatives. A direction that changes none of these moments to first order has zero expected information. ram_identification() counts singular values exceeding $10^{-8}$ times the largest and requires full column rank. It also requires the smallest information eigenvalue to exceed $10^{-8}$ times the largest before returning an inverse. These are scale-dependent numerical checks at one point. They do not prove global identification, optimizer convergence, or admissibility.
The local object J in this function is that moment Jacobian, returned as moment_jacobian. It differs from the parameter-map Jacobian supplied as jacobian. In the unrestricted full SEM their dimensions are $54\times30$ and $30\times30$, respectively. In the restricted growth model they are $14\times6$ and $9\times6$. The distinction matters when interpreting the returned uncertainty: working_covariance is the inverse information in free coordinates, covariance maps it to all stored parameters, and se follows the stored parameter order. If the rank or eigenvalue check fails, both covariance fields are NULL and the standard errors are missing.
Local identification distinguishes a parameter vector from neighboring allowed vectors through its observed distribution. Global identification requires the distinction throughout the parameter space. With a correctly specified regular model, an interior true parameter, local identification and nonsingular information, inverse information approximates the large-sample covariance in working coordinates. The delta method returns it to the reported scales:
\[\widehat{\operatorname{Cov}}(\hat\theta)=J I_u^{-1}J^\top.\]For a linear restriction $\theta=Kz$, the same expression uses $J=K$. Standard errors are the square roots of the diagonal entries. A disturbance variance describes variation in the modeled population; its standard error describes sampling variation of its estimate. The two quantities answer different questions.
The marker constraints in the full SEM remove scale indeterminacy. To expose it, temporarily free the first loading on $\xi$. If the factor is rescaled to $\xi^\ast =s\xi$ for positive $s$, divide its three loadings by $s$, replace $\phi$ by $s^2\phi$, and divide $a$ and $c^{\prime}$ by $s$. Every response distribution remains unchanged. Fixing the first loading at one forbids that rescaling. The following comparison adds exactly this redundant loading.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
identified <- ram_identification(truth, full, nrow(Y))
redundant <- full
redundant$parameter_table <- rbind(redundant$parameter_table,
data.frame(matrix = "A", row = 1, col = 10, parameter = "marker1"))
redundant$parameters <- c(redundant$parameters, "marker1")
redundant$transforms <- c(redundant$transforms, marker1 = "identity")
redundant_theta <- c(truth, marker1 = 1)
redundant_information <- ram_identification(redundant_theta, redundant, nrow(Y))
print(data.frame(model = c("fixed marker", "free marker"),
parameters = c(length(truth), length(redundant_theta)),
moment_rank = c(identified$rank, redundant_information$rank),
information_invertible = c(identified$valid, redundant_information$valid)))
record_check("identified_full_SEM", abs(identified$rank - length(truth)), 0)
record_check("redundant_marker_rank", abs(redundant_information$rank - length(truth)), 0)
1
2
3
model parameters moment_rank information_invertible
1 fixed marker 30 30 TRUE
2 free marker 31 30 FALSE
With the marker fixed, the 30-parameter model has moment-Jacobian rank 30 and passes the information inversion check. Freeing the marker raises the parameter count to 31 while the rank remains 30, so the routine withholds inverse-information standard errors. A parameter count smaller than the number of observable moments would not detect this problem. Similarly, the growth model must project onto its six free directions through growth_K before computing its inverse-information covariance.
For the full SEM’s indirect coefficient $h(\theta)=ab$, the relevant gradient entries are $\partial h/\partial a=b$ and $\partial h/\partial b=a$. Thus
\[\widehat{\operatorname{Var}}(\hat a\hat b) =\hat b^2\widehat{\operatorname{Var}}(\hat a) +\hat a^2\widehat{\operatorname{Var}}(\hat b) +2\hat a\hat b\widehat{\operatorname{Cov}}(\hat a,\hat b).\]The covariance term is needed because the coefficients are jointly estimated. A normal interval obtained from this first-order approximation is a large-sample summary; the product’s sampling distribution need not be symmetric, particularly when either coefficient is near zero. In lavaan, the information argument selects expected or observed information for standard errors.
7.6 BFGS, Fisher scoring, starting values, and improper solutions
The 30 parameters of the full SEM are now estimated from the nine observed responses. For normal ML, let $f(\theta)$ be the negative log likelihood and $f_{\rm sat}$ its value under the saturated model. The optimization criterion
\[\mathcal F(\theta)=\frac{f(\theta)-f_{\rm sat}}{n}\]has the same minimizer and expresses the likelihood loss per person. The default double-dogleg quasi-Newton search uses gradient changes to update curvature. BFGS also estimates curvature from gradient changes. Fisher scoring instead uses the model’s expected information.
For Fisher scoring, let $g$ be the gradient of $\mathcal F$ and $H=I_\theta/n$. Under a linear restriction $\theta=Kz$, the free-coordinate gradient and curvature are $K^\top g$ and $K^\top HK$. A damped step solves $(H+\lambda D)d=-g$ in the free coordinates, where $D$ is diagonal and based on the absolute diagonal entries of $H$. Damping limits poorly determined steps. A finite trial is accepted only if it decreases the criterion; the ratio of actual to predicted decrease controls the next damping value.
The implementation below uses a relative-gradient tolerance of $10^{-6}$ and an RMS parameter-step tolerance of $10^{-5}$ by default. The former scales gradient components by the current coordinate sizes and the criterion. The latter concerns change in the full parameter vector, including under a linear restriction. Its arguments fn, gr and he evaluate $\mathcal F$, its gradient and the expected information divided by $n$, respectively, at an original-scale parameter vector. An optional K has orthonormal columns spanning the allowed linear space. The following three code fragments form one function definition.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fisher_scoring <- function(fn, gr, he, par, control = list(), K = NULL) {
stopifnot(all(names(control) %in% c("max_iter", "tol_g", "tol_x")))
settings <- modifyList(list(max_iter = 200L, tol_g = 1e-6, tol_x = 1e-5), control)
unpack <- if (is.null(K)) function(z) z else function(z) as.numeric(K %*% z)
z <- if (is.null(K)) par else as.numeric(par %*% K)
evaluations <- c(objective = 0L, gradient = 0L, hessian = 0L)
value_at <- function(z) {
evaluations[1] <<- evaluations[1] + 1L
fn(unpack(z))
}
full_at <- function(z) {
x <- unpack(z)
evaluations[] <<- evaluations + 1L
g <- gr(x)
H <- he(x)
if (!is.null(K)) {
g <- as.numeric(g %*% K)
H <- crossprod(K, H %*% K)
}
list(fx = fn(x), g = g, H = (H + t(H)) / 2)
}
The search vector z contains the free coordinates. Without a restriction it is the original parameter vector; with a restriction, unpack(z) computes $Kz$ and the initial projection computes $K^\top\theta$. value_at() evaluates only the criterion for a proposed step. full_at() also obtains the gradient and curvature at the current point, projects them to the free coordinates when necessary, and removes numerical asymmetry from the curvature matrix. Separating these evaluations avoids reconstructing expected information for every rejected trial. The evaluation counters record these calls, with expected-information evaluations recorded under hessian.
The next part initializes the stopping diagnostics and attempts a damped step. A nonfinite initial criterion or derivative prevents entry into the iteration. Otherwise, each iteration first tests the scaled gradient and then increases damping until it obtains a finite decrease or reaches the refusal limit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Relative gradient: the scaled gradient over max(|F|, 1).
relative_gradient_F <- function(z, point)
max(abs(point$g) * pmax(abs(z), 1) / max(abs(point$fx), 1))
current <- full_at(z)
history <- list(list(par = unpack(z), value = current$fx, mu = NA_real_, ratio = NA_real_,
rms_step = NA_real_))
converged <- FALSE; iter <- 0L
mu <- 1e-4 # the damping
nu <- 2 # its growth factor after a refusal
reason <- if (any(!is.finite(current$g)) || any(!is.finite(current$H)) || !is.finite(current$fx)) "nonfinite_start" else
"iteration_limit"
if (reason == "nonfinite_start") settings$max_iter <- 0L
# One refusal: more damping, and a faster growth of the damping.
refuse <- function() {
mu <<- mu * nu
nu <<- 2 * nu
refused <<- refused + 1L
}
while (iter < settings$max_iter) {
if (relative_gradient_F(z, current) < settings$tol_g) {
converged <- TRUE
reason <- "small_relative_gradient"
break
}
iter <- iter + 1L
d <- pmax(abs(diag(current$H)), max(abs(diag(current$H)), 1) * 1e-8)
accepted <- FALSE; refused <- 0L; ratio <- NA_real_
while (!accepted && refused <= 25L && mu <= 1e12) {
damped <- current$H
diag(damped) <- diag(damped) + mu * d
R <- tryCatch(chol(damped), error = function(e) NULL)
if (is.null(R)) {
refuse()
next
}
# The damped Newton step, from the Cholesky factor of H + mu D.
step <- -backsolve(R, backsolve(R, current$g, transpose = TRUE))
z_new <- z + step
# The decrease predicted by the undamped quadratic model.
curvature <- sum(step * drop(current$H %*% step))
predicted <- -(sum(current$g * step) + 0.5 * curvature)
trial <- value_at(z_new)
actual <- current$fx - trial
if (!(is.finite(trial) && actual > 0)) {
refuse()
next
}
accepted <- TRUE
ratio <- if (is.finite(predicted) && predicted > 0) actual / predicted else 1
shrink <- max(1 / 3, 1 - (2 * ratio - 1)^3)
mu <- max(mu * shrink, 1e-12)
nu <- 2
}
Here d contains the diagonal entries of $D$, including a small positive floor. The two triangular solves compute the step from $H+\lambda D$ without forming its inverse; the code calls the damping parameter mu. For a proposed step $s$, predicted instead evaluates the undamped quadratic approximation, $-g^\top s-s^\top Hs/2$. The actual decrease is the current criterion minus the trial value. Acceptance requires a finite trial value and a positive actual decrease, rather than imposing a separate threshold on their ratio.
The ratio controls damping for the next attempt. Good agreement permits less damping, while poor agreement can increase it. If the predicted decrease is not positive and finite, the implementation assigns a ratio of one after a successful actual decrease. A failed factorization or a nondecreasing trial instead calls refuse(), which increases both damping and its growth factor. The current point remains unchanged during these refused attempts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
if (!accepted) {
converged <- relative_gradient_F(z, current) < sqrt(settings$tol_g)
reason <- if (converged) "no_step_kept_small_gradient" else "no_step_kept"
break
}
rms_step <- sqrt(mean((unpack(z_new) - unpack(z))^2))
z <- z_new
current <- full_at(z)
current$fx <- trial
history[[length(history) + 1L]] <- list(par = unpack(z), value = current$fx, mu = mu,
ratio = ratio, rms_step = rms_step)
if (any(!is.finite(current$g)) || any(!is.finite(current$H))) {
reason <- "nonfinite_derivatives"
break
}
if (rms_step < settings$tol_x) {
converged <- TRUE
reason <- "small_rms_step"
break
}
}
x <- unpack(z)
new_result(x, fn(x), gr(x), converged, reason, iter, evaluations, history, free = z)
}
After an accepted step, the routine recomputes the derivatives and records the full parameter vector, criterion, damping, ratio and RMS step in history. The returned par and gradient refer to the original parameter coordinates, whereas free contains the search vector z. With a restriction, stationarity concerns $K^\top g$; the full gradient need not vanish in directions the model excludes.
The stopping reasons describe distinct tests. small_relative_gradient uses the specified gradient tolerance. small_rms_step uses change in parameters and does not establish a small score. If no trial is accepted, the fallback no_step_kept_small_gradient uses the square root of tol_g, which is $10^{-3}$ under the defaults, rather than the usual $10^{-6}$ test. Otherwise the routine reports no_step_kept without convergence. Nonfinite derivatives or exhaustion of iterations also leave convergence false. The comparison below therefore reports the final gradient as well as the convergence flag.
One fitting function for three searches
The fitting function below supplies the common criterion to scoring, BFGS or double dogleg and then evaluates the final model on its original statistical scale. The scoring routine and parts of the default fit use adaptations of lavaan routines (code/NOTICE.md). The definition is shown in three parts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
sem_fit <- function(spec, data, estimator = "ML", start, method = "dogleg", objective = NULL,
saturated = NULL, K = NULL, control = list()) {
stopifnot(method %in% c("dogleg", "BFGS", "scoring"))
if (!is.null(K)) {
stopifnot(is.matrix(K), nrow(K) == length(start), ncol(K) > 0L, ncol(K) <= nrow(K),
all(is.finite(K)), qr(K)$rank == ncol(K))
# The columns span the allowed parameter space. Orthonormal columns give z = K' x.
if (!isTRUE(all.equal(unname(crossprod(K)), diag(ncol(K)), tolerance = 1e-12)))
K <- qr.Q(qr(K))
}
map <- ram_identity(spec)
obj <- if (is.null(objective)) make_ram_objective(spec, data, estimator, map) else objective
n <- data$n
if (obj$estimator %in% c("ML", "FIML")) {
reference <- if (is.null(saturated)) ram_criterion(data$mean, data$S, data, "ML") else saturated
fn <- function(x) (obj$fn(x) - reference) / n
gr <- function(x) obj$gr(x) / n
} else {
reference <- 0
fn <- obj$fn
gr <- obj$gr
}
In sem_fit(), map <- ram_identity(spec) means that the constructed objective takes original-scale parameters. A residual variance start of $0.5$ is a variance of $0.5$, regardless of the optional transformation label in the specification. A separately supplied objective must use the same coordinates. If K is supplied, nonorthonormal columns are replaced by an orthonormal basis spanning the same allowed space; this changes free coordinates without changing the linear restriction.
For normal likelihoods, reference is the saturated negative log likelihood. Subtraction changes the objective’s origin, and division by n gives $\mathcal F$ and its gradient per person. The least squares objectives already use their stated scaling and pass through unchanged. The following branches search these same functions in the allowed directions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
if (method == "dogleg") {
Kz <- if (is.null(K)) diag(length(start)) else K
z0 <- as.numeric(start %*% Kz)
large <- vapply(z0, function(v) isTRUE(abs(v) > 1.0), TRUE) # |start| > 1: scale 1 / |start|
scale <- rep(1.0, length(z0))
scale[large] <- abs(1.0 / z0[large])
run <- dogleg_minimize(z0, function(z) fn(as.numeric(Kz %*% z)),
function(z) as.numeric(gr(as.numeric(Kz %*% z)) %*% Kz), scale = scale,
control = modifyList(list(abs_tol = .Machine$double.eps * 10, false_tol = 2.2e-14,
max_evals = 20000L, max_iter = 10000L, rel_tol = 1e-10, step_hi = 1.0, step_lo = 1.0,
x_tol = 1.5e-8), control))
optimizer <- list(par = as.numeric(Kz %*% run$par), value = run$objective,
converged = run$convergence == 0L, reason = run$message, iterations = run$iterations,
evaluations = c(objective = run$evaluations[[1]], gradient = run$evaluations[[2]]),
run = run)
} else if (method == "scoring") {
stopifnot(obj$estimator == "ML")
he <- function(x) ram_information(x, spec, n) / n
optimizer <- fisher_scoring(fn, gr, he, start, control, K)
} else {
z0 <- if (is.null(K)) start else as.numeric(crossprod(K, start))
free_fn <- if (is.null(K)) fn else function(z) fn(as.numeric(K %*% z))
free_gr <- if (is.null(K)) gr else function(z) as.numeric(crossprod(K, gr(as.numeric(K %*% z))))
scale <- rep(1, length(z0))
large <- abs(z0) > 1
scale[large] <- abs(1 / z0[large])
optimizer <- bfgs(free_fn, free_gr, z0, modifyList(list(maxit = 10000L, rel_tol = 1e-10,
abs_tol = 1e-20, par_scale = scale), control))
if (!is.null(K)) {
# Store search diagnostics in their original free coordinates and return the full estimates.
optimizer$free <- optimizer$par
optimizer$free_gradient <- optimizer$gradient
optimizer$par <- as.numeric(K %*% optimizer$free)
optimizer$gradient <- gr(optimizer$par)
}
}
The double-dogleg and BFGS branches evaluate the full model at $Kz$ and project its gradient back to the search coordinates. Their starting-value scales affect numerical steps, not the definitions of the statistical parameters. Scoring instead supplies ram_information(...)/n as curvature. Its restriction to complete-data ML prevents substituting that information for the curvature of a different criterion. Under BFGS with a restriction, the original free-coordinate estimates and gradient are retained before the reported parameter vector is expanded.
The last part evaluates the unscaled objective at the returned parameters. It computes complete-data ML information in the same allowed directions and checks disturbance admissibility separately from optimizer convergence.
1
2
3
4
5
6
7
8
9
10
11
final <- obj$evaluate(optimizer$par)
jacobian <- if (is.null(K)) diag(length(start)) else K
diagnostic <- if (obj$estimator == "ML") ram_identification(final$mapped$theta, spec, n,
jacobian) else NULL
list(theta = final$mapped$theta, model = final$model, value = final$value,
fit_function = optimizer$value, gradient = final$gradient, optimizer = optimizer,
information = diagnostic, admissibility = ram_admissibility(final$mapped$theta, spec),
estimator = obj$estimator, method = method, spec = spec, data = data, map = map,
approximation = "exact normal moments", divisor = data$divisor,
loglik = if (obj$estimator %in% c("ML", "FIML")) -final$value else NA_real_)
}
The returned theta contains parameter estimates and model their implied moments and RAM arrays. For ML, value is the full-sample negative log likelihood, loglik is its negative, and gradient differentiates that full-sample value. In contrast, fit_function and the optimizer’s criterion value are $\mathcal F$. Consequently the next table divides fit$gradient by the number of people before comparing stationarity across methods. For GLS and ULS, value and fit_function instead use the same least squares scale, and loglik is missing.
The field information contains the rank diagnostics and expected-information standard errors for complete-data ML. It is NULL for full information maximum likelihood (FIML) and covariance-only least squares, which require their own uncertainty calculations. The separate admissibility field reports the disturbance check. These fields allow the same fitted object to support parameter tables, likelihood comparisons and diagnostics without treating a convergence flag as evidence for all three.
Starting values and the full SEM fit
Each of the three searches needs a starting vector. Three indicators offer a data-based start for each measurement block. With the first loading fixed at one and independent response errors, $s_{12}s_{13}/s_{23}$ equals that block’s marginal factor variance when the covariances take their population values and $s_{23}\ne0$. Dividing $s_{12}$ and $s_{13}$ by that variance then recovers the other two loadings. For the endogenous factors, this marginal variance includes variation transmitted by structural paths; it is not their structural disturbance variance. Sampling noise can make the ratio invalid or unstable. The starting rule below bounds a finite positive variance between 10% and 90% of the marker’s sample variance, falls back to half that variance otherwise, and bounds the loadings so response-error starts remain positive. These bounds choose an initial point; they are not constraints on the estimates.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
full_sem_start <- function(data, spec = full_sem_spec()) {
start <- setNames(numeric(length(spec$parameters)), spec$parameters)
residuals <- numeric(9)
latent_variances <- numeric(3)
for (g in 1:3) {
rows <- (3 * g - 2):(3 * g)
s <- data$S[rows, rows]
denominator <- s[2, 3]
variance <- if (abs(denominator) > 1e-10) s[1, 2] * s[1, 3] / denominator else NA_real_
if (!is.finite(variance) || variance <= 0) variance <- .5 * s[1, 1]
variance <- min(max(variance, .1 * s[1, 1]), .9 * s[1, 1])
loadings <- s[1, 2:3] / variance
bound <- sqrt(.9 * diag(s)[2:3] / variance)
loadings <- pmin(pmax(loadings, -bound), bound)
start[paste0("loading", rows[2:3])] <- loadings
residuals[rows] <- pmax(diag(s) - c(1, loadings)^2 * variance, .1 * diag(s))
latent_variances[g] <- variance
}
start[paste0("residual", 1:9)] <- residuals
start[c("phi", "psi1", "psi2")] <- latent_variances
if ("intercept1" %in% names(start)) start[paste0("intercept", 1:9)] <- data$mean
start
}
start <- full_sem_start(full_data, full)
Within each measurement block, residuals subtracts the proposed factor contribution from the observed variances and enforces the positive starting bound. The initialized vector leaves the structural coefficients at zero, so the three initial marginal factor variances can also serve as their disturbance variances. Observed intercepts start at sample means. This produces an initially independent set of factors with a positive diagonal disturbance covariance. It uses the observations and measurement pattern rather than simulated latent values. All three methods receive the same start.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ml <- sem_fit(full, full_data, start = start)
bfgs_fit <- sem_fit(full, full_data, start = start, method = "BFGS")
scoring_fit <- sem_fit(full, full_data, start = start, method = "scoring")
optimizer_table <- do.call(rbind, lapply(list(dogleg = ml, BFGS = bfgs_fit,
scoring = scoring_fit), function(fit) {
data.frame(nll = fit$value, converged = fit$optimizer$converged,
iterations = fit$optimizer$iterations,
gradient_per_person = max(abs(fit$gradient)) / full_data$n,
moment_rank = fit$information$rank,
smallest_disturbance_eigenvalue = fit$admissibility$smallest_disturbance_eigenvalue)
}))
print(optimizer_table)
print(data.frame(parameter = full$parameters, truth = unname(truth),
estimate = unname(ml$theta), SE = ml$information$se), row.names = FALSE)
record_check("main_fit_converged", as.numeric(!ml$optimizer$converged), 0)
record_check("main_fit_gradient_per_person", max(abs(ml$gradient)) / full_data$n, 2e-5)
record_check("main_fit_disturbance_PSD", max(0, -ml$admissibility$smallest_disturbance_eigenvalue), 1e-8)
saveRDS(list(full = ml, BFGS = bfgs_fit, scoring = scoring_fit),
file.path("data/derived/ch07", "full-fits.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
nll converged iterations gradient_per_person moment_rank smallest_disturbance_eigenvalue
dogleg 5911.739 TRUE 22 6.808658e-08 30 0.4239944
BFGS 5911.739 TRUE 21 3.594761e-07 30 0.4239944
scoring 5911.739 TRUE 6 1.425692e-06 30 0.4239938
parameter truth estimate SE
loading2 0.80 0.85838266 0.05313104
loading3 0.70 0.71333815 0.04743240
loading5 0.90 0.93482131 0.05136734
loading6 0.75 0.73830896 0.04446951
loading8 0.85 0.80241012 0.05193982
loading9 0.65 0.68375804 0.04839527
a 0.60 0.62854208 0.05570631
b 0.50 0.48462486 0.06541238
cprime 0.20 0.25291744 0.06483669
residual1 0.50 0.57236989 0.05743332
residual2 0.50 0.44198925 0.04324430
residual3 0.50 0.47724725 0.03875045
residual4 0.50 0.42399444 0.04672416
residual5 0.50 0.51780422 0.04754638
residual6 0.50 0.50166282 0.03934328
residual7 0.50 0.49853508 0.05609018
residual8 0.50 0.48422636 0.04360114
residual9 0.50 0.54718824 0.04243240
phi 1.00 0.98336417 0.10177899
psi1 0.70 0.63253044 0.06864119
psi2 0.60 0.52817058 0.06409594
intercept1 0.00 0.14944473 0.05578054
intercept2 0.20 0.21600108 0.04830222
intercept3 -0.20 -0.09872463 0.04421840
intercept4 0.50 0.51086665 0.05375905
intercept5 0.30 0.33951479 0.05310494
intercept6 0.10 0.11602442 0.04600484
intercept7 -0.10 -0.02104470 0.05442289
intercept8 0.40 0.51933028 0.04725992
intercept9 0.20 0.32754421 0.04486603
All three searches report convergence and a negative log likelihood of $5911.739$ at the printed precision. The default fit has a maximum gradient per person of $6.81\times10^{-8}$, moment-Jacobian rank 30, and a smallest disturbance eigenvalue of about $0.424$. These diagnostics support interpreting it as an admissible, numerically stationary fit. Fisher scoring uses six iterations, compared with 22 for double dogleg and 21 for BFGS, but each scoring iteration constructs expected information. Iteration counts alone therefore do not measure computational cost, and agreement among the searches does not establish a global optimum.
The structural estimates are $\hat a=0.6285$ with standard error (SE) $0.0557$, $\hat b=0.4846$ with SE $0.0654$, and $\hat c^{\prime}=0.2529$ with SE $0.0648$. Their generating values were $0.6$, $0.5$ and $0.2$. The fitted disturbance variances, $\hat\phi=0.9834$, $\hat\psi_1=0.6325$ and $\hat\psi_2=0.5282$, retain their distinct roles: the latter two are unexplained variances in the structural equations, not the marginal variances of the endogenous factors. Sampling variation is expected throughout the parameter table; equality with the generating values is not an optimizer test.
The next function applies the delta method to the direct, indirect and total coefficients. Its Jacobian uses the parameter names, so the covariance terms are taken from the joint fitted covariance in the correct order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
structural_effects <- function(theta, covariance) {
a <- unname(theta["a"])
b <- unname(theta["b"])
cprime <- unname(theta["cprime"])
derivative <- matrix(0, 3, length(theta), dimnames = list(
c("direct", "indirect", "total"), names(theta)))
derivative["direct", "cprime"] <- 1
derivative["indirect", c("a", "b")] <- c(b, a)
derivative["total", c("a", "b", "cprime")] <- c(b, a, 1)
se <- if (is.null(covariance)) rep(NA_real_, 3) else
sqrt(diag(derivative %*% covariance %*% t(derivative)))
estimate <- c(cprime, a * b, cprime + a * b)
data.frame(effect = rownames(derivative), estimate = estimate, SE = se,
lower = estimate - qnorm(.975) * se, upper = estimate + qnorm(.975) * se)
}
The three rows of derivative correspond to $c^{\prime}$, $ab$ and $c^{\prime}+ab$; its columns follow names(theta). The supplied parameter covariance must follow that same order. The product derivative %*% covariance %*% t(derivative) is therefore the joint sampling covariance of the three derived coefficients, and its diagonal supplies their squared standard errors. Each returned row contains the estimate, standard error and endpoints of a 95% normal interval. A missing covariance produces missing uncertainty entries while still allowing the coefficients to be calculated.
1
print(structural_effects(ml$theta, ml$information$covariance), row.names = FALSE)
1
2
3
4
effect estimate SE lower upper
direct 0.2529174 0.06483669 0.1258399 0.3799950
indirect 0.3046071 0.04665936 0.2131565 0.3960578
total 0.5575246 0.05623567 0.4473047 0.6677444
The indirect estimate is $\hat a\hat b=0.3046$, with delta-method SE $0.0467$ and a 95% normal interval from $0.2132$ to $0.3961$. Adding the direct estimate gives a total coefficient of $0.5575$, with SE $0.0562$ and interval from $0.4473$ to $0.6677$. The total’s standard error is not the sum of the two component standard errors: it uses their covariance through the displayed Jacobian.
The direct coefficient describes $\xi$’s contribution at a given $\eta_1$; the indirect coefficient describes the two-path product; and the total combines them. Their reported units depend on the marker scales. These normal intervals quantify uncertainty under the fitted statistical model. They do not add causal identification to its arrows.
Disturbance admissibility and covariance fitting
An optimizer can produce a positive definite response covariance while a disturbance variance is negative. The next calculation deliberately replaces the first response-error variance by $-0.01$ at otherwise generating parameters. It asks whether the response covariance still permits a likelihood evaluation, then separately inspects $S$.
1
2
3
4
5
6
7
improper_theta <- truth
improper_theta["residual1"] <- -.01
improper_moments <- ram_implied(improper_theta, full)
print(c(smallest_response_eigenvalue = min(eigen(improper_moments$covariance,
symmetric = TRUE, only.values = TRUE)$values),
smallest_disturbance_eigenvalue =
ram_admissibility(improper_theta, full)$smallest_disturbance_eigenvalue))
1
2
smallest_response_eigenvalue smallest_disturbance_eigenvalue
0.185776 -0.010000
The response covariance has smallest eigenvalue $0.185776$ and therefore passes its positive definiteness check, although $S$ has smallest eigenvalue $-0.01$. This deliberate example separates likelihood evaluation from disturbance admissibility. A negative error variance is incompatible with the specified population decomposition even when the normal density for the observed responses exists. For a correlated block, positive diagonal entries alone are insufficient: $G$ in the growth model must satisfy $g_{00}\geq0$, $g_{11}\geq0$ and $g_{01}^2\leq g_{00}g_{11}$. Near-boundary estimates also require care with ordinary inverse-information intervals and chi-square approximations.
For GLS and ULS, the response intercepts are fixed at their sample means and only the 21 covariance parameters are fitted. The different criteria generally give different estimates even with the same measurement and structural restrictions.
1
2
3
4
5
6
7
8
9
10
covariance_fits <- lapply(c("ML", "GLS", "ULS"), function(estimator) {
sem_fit(cov_spec, full_data, estimator = estimator,
start = full_sem_start(full_data, cov_spec))
})
names(covariance_fits) <- c("ML", "GLS", "ULS")
print(do.call(rbind, lapply(covariance_fits, function(fit) {
c(a = fit$theta["a"], b = fit$theta["b"], cprime = fit$theta["cprime"],
criterion = fit$value, gradient_max = max(abs(fit$gradient)),
converged = fit$optimizer$converged)
})))
1
2
3
4
a.a b.b cprime.cprime criterion gradient_max converged
ML 0.6285421 0.4846249 0.2529174 5.911739e+03 3.404329e-05 1
GLS 0.6306359 0.4796526 0.2581135 1.521225e-02 1.026103e-07 1
ULS 0.6117754 0.4872108 0.2470666 6.130963e-03 1.160681e-07 1
The covariance-only ML fit reproduces the full ML structural estimates because the nine free means in the full fit can attain the sample means. GLS gives $\hat a=0.6306$, $\hat b=0.4797$ and $\hat c^{\prime}=0.2581$; ULS gives $0.6118$, $0.4872$ and $0.2471$. These differences reflect the criteria’s covariance weights. Their reported criterion values have different scales and cannot rank the estimators by fit.
The GLS and ULS fits have no estimated mean parameters. The complete-data normal expected information is not automatically their sampling covariance; reporting ML standard errors for them would require an additional justification absent from these calls. The lavaan package minimizes its fitting function with nlminb() by default.
7.7 Full information maximum likelihood with missing-data patterns
So far every person has supplied all nine responses. Suppose response one is always observed, response two is more often missing when response one is high, and response eight is independently missing with probability $0.2$. The next code imposes this mechanism on the complete nine-response sample. The missing probability for response two is $\operatorname{logit}^{-1}(-1+0.4y_{i1})$; all other responses remain recorded.
1
2
3
4
5
set.seed(70702)
Y_missing <- Y
Y_missing[runif(nrow(Y)) < plogis(-1 + .4 * Y[, 1]), 2] <- NA
Y_missing[runif(nrow(Y)) < .2, 8] <- NA
saveRDS(Y_missing, file.path("data/source/ch07", "FULLSEM9-missing.rds"))
This mechanism is missing at random (MAR): once the observed values are given, its probability does not depend on the values behind the missing entries. Under MAR and distinct response-model and missingness parameters, the missingness probability can be omitted when maximizing the response likelihood. Discarding incomplete rows changes the distribution of the always-observed first response because its value affects selection. It also discards the other recorded responses of those people.
FIML instead uses each person’s marginal density for the observed responses. Let $O_i$ be the observed indices, $p_i$ their count, and $e_i=y_{i,O_i}-\mu_{O_i}$. Integration over the unobserved coordinates of the normal vector gives
\[\ell_i=-\frac12\left\{p_i\log(2\pi)+\log|\Sigma_{O_iO_i}| +e_i^\top\Sigma_{O_iO_i}^{-1}e_i\right\}.\]The full SEM still determines one nine-dimensional mean and covariance. Each person’s contribution selects the appropriate subvector and submatrix. A missing response is not assigned a fitted value and treated as observed. A row with no observed responses has a zero log-density contribution to this response likelihood; the generated example has no such rows.
For a group sharing indices $O_r$, let $n_r$ be its size, $\bar y_r$ its mean vector, and $S_r$ its sample covariance with divisor $n_r$. With $P_r=\Sigma_{O_rO_r}^{-1}$ the pattern’s negative log likelihood is
\[f_r=\frac{n_r}{2}\left\{p_r\log(2\pi)+\log|\Sigma_{O_rO_r}| +\operatorname{tr}(P_rS_r) +(\bar y_r-\mu_{O_r})^\top P_r(\bar y_r-\mu_{O_r})\right\}.\]Grouping avoids refactoring the same model submatrix for every row. The means observed in different patterns can differ because selection depends on response one. These are sample summaries of the selected rows, while $\mu$ remains the common population mean. The computation does not assume a separate population model conditional on each pattern. A pattern sample covariance need not be invertible because only the model covariance is inverted.
Grouping people by missingness pattern
The first routine groups people with the same observed-response indices and summarizes their recorded values. Those summaries will permit one likelihood calculation per pattern.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fiml_patterns <- function(Y) {
Y <- as.matrix(Y)
stopifnot(all(is.finite(Y) | is.na(Y)))
observed <- !is.na(Y)
keys <- apply(observed, 1, paste0, collapse = "")
lapply(split(seq_len(nrow(Y)), keys), function(rows) {
O <- which(observed[rows[1], ])
X <- Y[rows, O, drop = FALSE]
mean <- colMeans(X)
centered <- sweep(X, 2, mean, "-")
list(rows = rows, observed = O, n = length(rows), p = length(O), mean = mean,
S = crossprod(centered) / length(rows))
})
}
Each element returned by fiml_patterns() describes one pattern. rows contains the original person indices and observed the recorded response indices; n and p give their respective counts. The fields mean and S contain the $p_r$ means and $p_r\times p_r$ covariance in that observed order, with divisor $n_r$. For a pattern missing responses two and eight, the seven columns are responses one, three, four, five, six, seven and nine. This structure has the fields needed by ram_criterion() without assigning values to the missing responses.
An independent calculation evaluates the marginal normal log density for each person. It preserves the original row order, permitting a check that the grouped sum uses exactly the same observations.
1
2
3
4
5
6
7
8
9
normal_contributions <- function(Y, mu, Sigma) {
vapply(seq_len(nrow(Y)), function(i) {
O <- which(!is.na(Y[i, ]))
if (!length(O)) return(0.0)
R <- chol(Sigma[O, O, drop = FALSE])
r <- forwardsolve(t(R), Y[i, O] - mu[O])
-.5 * (length(O) * log(2 * pi) + 2 * sum(log(diag(R))) + sum(r^2))
}, 0.0)
}
Here the triangular solve transforms the observed residual so that sum(r^2) equals its precision-weighted quadratic form. The log determinant uses only the observed covariance submatrix. The return value has one log density per person, and its sum is a log likelihood. The objective constructed next returns the negative of that sum. This sign difference is why the later check adds the objective to the summed contributions.
For a parameter $\theta_j$, the pattern gradient contribution is
\[q_r^\top(\dot\mu_j)_{O_r} +\operatorname{tr}\left[Q_r^\top(\dot\Sigma_j)_{O_rO_r}\right],\]where $q_r,Q_r$ are the mean and covariance sensitivities for that pattern. The contributions sum before the parameter-map Jacobian is applied. The following objective combines this derivative with the grouped negative log likelihood.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fiml_nll <- function(spec, Y, map = function(u) ram_map(u, spec)) {
patterns <- fiml_patterns(Y)
evaluate <- function(u, derivatives = TRUE) {
mapped <- map(u)
model <- ram_implied(mapped$theta, spec)
D <- if (derivatives) ram_derivatives(mapped$theta, spec) else NULL
value <- 0
original <- numeric(length(u))
for (pattern in patterns) {
O <- pattern$observed
if (!length(O)) next
mu <- model$mean[O]
Sigma <- model$covariance[O, O, drop = FALSE]
value <- value + ram_criterion(mu, Sigma, pattern, "ML")
if (derivatives) {
Q <- ram_sensitivity(mu, Sigma, pattern, "ML")
for (j in seq_along(u)) original[j] <- original[j] +
sum(Q$mean * D$mean[O, j]) + sum(as.vector(Q$covariance) * D$covariance[O, O, j, drop = FALSE])
}
}
list(value = value, gradient = if (derivatives) drop(crossprod(mapped$jacobian, original)) else NULL,
model = model, mapped = mapped)
}
list(fn = function(u) tryCatch(evaluate(u, FALSE)$value, error = function(e) Inf),
gr = function(u) evaluate(u)$gradient, evaluate = evaluate, patterns = patterns,
contributions = function(u) {
model <- ram_implied(map(u)$theta, spec)
normal_contributions(Y, model$mean, model$covariance)
}, spec = spec, map = map, estimator = "FIML")
}
The data patterns are computed once when fiml_nll() constructs the objective. At each new parameter vector, evaluate() obtains one full mean and covariance, then selects each pattern’s observed entries. Its D$mean[O, j] and D$covariance[O, O, j, drop = FALSE] select the same coordinates from parameter $j$’s derivatives. The products with Q implement the two terms above, accumulating a full-sample gradient in original before applying the chain rule.
As in the complete-data objective, fn, gr and evaluate expose the value, gradient and combined evaluation. The additional patterns field supports inspection of the grouping, and contributions returns individual log densities at a supplied vector. The following call uses ram_identity(full) so all these functions accept original-scale parameters. The three checks then compare grouped and individual likelihoods, FIML and complete-data likelihoods when nothing is missing, and analytic and numerical gradients at the same vector.
1
2
3
4
5
6
7
8
9
10
11
12
13
fiml <- fiml_nll(full, Y_missing, map = ram_identity(full))
print(do.call(rbind, lapply(fiml$patterns, function(pattern) {
data.frame(observed = paste(pattern$observed, collapse = ","), people = pattern$n)
})), row.names = FALSE)
pattern_gap <- abs(fiml$fn(truth) + sum(fiml$contributions(truth)))
complete_objective <- fiml_nll(full, Y, map = ram_identity(full))
complete_gap <- abs(complete_objective$fn(truth) - objective_natural$fn(truth))
missing_gradient_gap <- max(abs(fiml$gr(truth) - num_grad(fiml$fn, truth)$gradient))
print(c(pattern_sum_gap = pattern_gap, complete_likelihood_gap = complete_gap,
missing_gradient_gap = missing_gradient_gap))
record_check("FIML_pattern_sum", pattern_gap, 1e-8)
record_check("FIML_complete_identity", complete_gap, 1e-8)
record_check("FIML_gradient", missing_gradient_gap, 3e-5)
1
2
3
4
5
6
7
observed people
1,3,4,5,6,7,9 22
1,3,4,5,6,7,8,9 113
1,2,3,4,5,6,7,9 64
1,2,3,4,5,6,7,8,9 301
pattern_sum_gap complete_likelihood_gap missing_gradient_gap
4.547474e-12 0.000000e+00 4.086194e-07
The four observed patterns contain 22, 113, 64 and 301 people, totaling the original 500. Only the final pattern is complete. The grouped negative log likelihood agrees with the negative sum of individual log densities to about $4.55\times10^{-12}$, and the complete-data identity has zero discrepancy at the reported precision. The largest gradient discrepancy is $4.09\times10^{-7}$. These checks isolate grouping and selection errors from optimization.
Saturated reference and FIML uncertainty
A FIML fit is judged against a saturated model fitted to the same incomplete data. The incomplete-data saturated normal model estimates an unrestricted common mean and covariance by EM. Conditional expectations of missing coordinates supply the first moments. Second moments also require their conditional covariance; filling missing entries with conditional means alone would omit that uncertainty. For observed set $O$ and missing set $M$,
\[E(y_M\mid y_O)=\mu_M+\Sigma_{MO}\Sigma_{OO}^{-1}(y_O-\mu_O),\qquad \operatorname{Var}(y_M\mid y_O)=\Sigma_{MM}-\Sigma_{MO}\Sigma_{OO}^{-1}\Sigma_{OM}.\]The next routine accumulates both terms, updates the normal moments, and stops when every mean and distinct covariance changes by less than the requested tolerance. The observed column means and diagonal covariance supply starting values, rather than final saturated estimates. Its M step and numerical covariance safeguard follow the book’s implementation adapted from lavaan (code/NOTICE.md). The two code fragments form one EM function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
saturated_em <- function(Y, tol = 1e-5, maxit = 500L) {
n <- nrow(Y)
p <- ncol(Y)
mu <- colMeans(Y, na.rm = TRUE)
Sigma <- diag(colMeans(sweep(Y, 2, mu)^2, na.rm = TRUE), p)
patterns <- fiml_patterns(Y)
vech <- function(A) A[lower.tri(A, diag = TRUE)]
old <- c(mu, vech(Sigma))
converged <- FALSE
for (iteration in seq_len(maxit)) {
T1 <- numeric(p)
T2 <- matrix(0, p, p)
for (pattern in patterns) {
O <- pattern$observed
M <- setdiff(seq_len(p), O)
rows <- Y[pattern$rows, , drop = FALSE]
filled <- rows
extra <- matrix(0, p, p)
if (length(M)) {
B <- Sigma[M, O, drop = FALSE] %*% solve(Sigma[O, O, drop = FALSE])
filled[, M] <- sweep(sweep(rows[, O, drop = FALSE], 2, mu[O]) %*% t(B), 2, mu[M], "+")
extra[M, M] <- pattern$n * (Sigma[M, M, drop = FALSE] - B %*% Sigma[O, M, drop = FALSE])
}
T1 <- T1 + colSums(filled)
T2 <- T2 + crossprod(filled) + extra
}
Within a pattern, B is the conditional regression coefficient $\Sigma_{MO}\Sigma_{OO}^{-1}$; it is local to this function and differs from the inverse RAM system matrix. The matrix filled retains the observed entries and places conditional means in the missing positions. Its column sums contribute $\sum_i E(y_i\mid y_{i,O_i})$ to T1. Its cross-product supplies only the outer products of those conditional means, so the second moment needs an additional term.
Every person in a pattern has the same conditional covariance for the missing coordinates. The assignment to extra[M, M] multiplies that covariance by the pattern count. Other entries of extra are zero because the observed values are fixed under this conditioning. Thus crossprod(filled) + extra contributes $\sum_i E(y_i y_i^\top\mid y_{i,O_i})$ to T2. For the pattern missing responses two and eight, the correction occupies their $2\times2$ block, including their conditional covariance. Temporary conditional means alone would omit this part of the second moment.
The M step divides both totals by the number of people and subtracts the outer product of the updated mean from the second moment. The remaining code checks the covariance and the change from the preceding iteration.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mu <- T1 / n
Sigma <- T2 / n - tcrossprod(mu)
# A nearly singular update: a small ridge on the variances.
smallest <- min(eigen(Sigma, symmetric = TRUE, only.values = TRUE)$values)
if (smallest < 1e-6) diag(Sigma) <- diag(Sigma) + max(diag(Sigma)) * 1e-8
new <- c(mu, vech(Sigma))
if (max(abs(new - old)) < tol) {
converged <- TRUE
break
}
old <- new
}
list(mean = mu, covariance = Sigma, iterations = iteration, converged = converged,
loglik = sum(normal_contributions(Y, mu, Sigma)))
}
The returned mean and covariance are the saturated estimates at termination; iterations and converged report the change-based stopping check. The local vech() selects each distinct covariance entry once for that check. The small diagonal adjustment protects a nearly singular update; an adjusted covariance is not itself evidence of identification. The field loglik sums marginal log densities for the original incomplete rows. The temporary filled matrices are used for EM moments and never replace those rows in the structural-model likelihood.
The following fit requires convergence of the saturated calculation and passes its negative log likelihood as the reference in sem_fit(). Its moments also supply starting values. The objective remains fiml, which evaluates the recorded responses, while the complete-case fit uses only fully observed rows. For uncertainty, num_hess() differentiates the analytic gradient of the full observed-data negative log likelihood at the FIML estimate. This Hessian already has full-sample scaling; its inverse, when positive definite, supplies missing_covariance, and the square roots of its diagonal supply missing_se in parameter order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
saturated_missing <- saturated_em(Y_missing, tol = 1e-8, maxit = 2000L)
stopifnot(saturated_missing$converged)
missing_start_data <- list(S = saturated_missing$covariance, mean = saturated_missing$mean)
missing_fit <- sem_fit(full, list(n = nrow(Y_missing), divisor = "observed patterns"),
start = full_sem_start(missing_start_data), objective = fiml,
saturated = -saturated_missing$loglik)
complete_case_data <- sem_data(Y_missing[complete.cases(Y_missing), , drop = FALSE])
complete_case_fit <- sem_fit(full, complete_case_data,
start = full_sem_start(complete_case_data))
missing_H <- num_hess(fiml$fn, missing_fit$theta, gr = fiml$gr, step = 1e-4)$hessian
missing_eigenvalues <- eigen(missing_H, symmetric = TRUE, only.values = TRUE)$values
missing_covariance <- if (min(missing_eigenvalues) > 0) chol2inv(chol(missing_H)) else NULL
missing_se <- if (is.null(missing_covariance)) rep(NA_real_, length(truth)) else
sqrt(diag(missing_covariance))
print(data.frame(method = c("FIML", "complete cases"),
people = c(nrow(Y_missing), complete_case_data$n),
a = c(missing_fit$theta["a"], complete_case_fit$theta["a"]),
b = c(missing_fit$theta["b"], complete_case_fit$theta["b"]),
cprime = c(missing_fit$theta["cprime"], complete_case_fit$theta["cprime"]),
nll = c(missing_fit$value, complete_case_fit$value),
converged = c(missing_fit$optimizer$converged, complete_case_fit$optimizer$converged)))
print(data.frame(parameter = full$parameters, estimate = unname(missing_fit$theta),
observed_information_SE = missing_se), row.names = FALSE)
record_check("FIML_fit_converged", as.numeric(!missing_fit$optimizer$converged), 0)
record_check("FIML_fit_gradient_per_person", max(abs(missing_fit$gradient)) / nrow(Y), 2e-5)
saveRDS(list(fit = missing_fit, saturated = saturated_missing,
observed_covariance = missing_covariance),
file.path("data/derived/ch07", "missing-fit.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
method people a b cprime nll converged
1 FIML 500 0.6307090 0.4862227 0.2465090 5639.602 TRUE
2 complete cases 301 0.6260174 0.4816871 0.2451147 3492.364 TRUE
parameter estimate observed_information_SE
loading2 0.80023779 0.06074672
loading3 0.71996041 0.05218964
loading5 0.93604691 0.05129662
loading6 0.73566151 0.04443561
loading8 0.80493029 0.05259850
loading9 0.67770149 0.04942453
a 0.63070899 0.05687834
b 0.48622271 0.06736121
cprime 0.24650896 0.06814165
residual1 0.57973651 0.06450002
residual2 0.47210678 0.05051966
residual3 0.47173196 0.04145607
residual4 0.42298450 0.04681966
residual5 0.51457844 0.04753361
residual6 0.50510068 0.03953867
residual7 0.48137665 0.05806546
residual8 0.44020703 0.04456425
residual9 0.54740818 0.04320451
phi 0.97599747 0.10560648
psi1 0.63378743 0.07049937
psi2 0.55105661 0.06705463
intercept1 0.14944485 0.05578053
intercept2 0.20276909 0.05175814
intercept3 -0.09872430 0.04421840
intercept4 0.51086686 0.05375905
intercept5 0.33951504 0.05310494
intercept6 0.11602461 0.04600484
intercept7 -0.02104449 0.05442288
intercept8 0.51277403 0.04917987
intercept9 0.32754437 0.04486603
FIML uses recorded responses from all 500 people and estimates $a=0.6307$, $b=0.4862$ and $c^{\prime}=0.2465$. The corresponding observed-information standard errors are $0.0569$, $0.0674$ and $0.0681$. The complete-case fit uses 301 people and gives $0.6260$, $0.4817$ and $0.2451$. These structural estimates are similar in this realization, but similarity in one sample does not establish that complete-case analysis is unbiased under the selection mechanism.
The negative log likelihoods, $5639.602$ for FIML and $3492.364$ for complete cases, contain different observations and normalizing dimensions. Their raw difference is therefore not a likelihood-ratio test of the two methods, and the smaller complete-case value is not evidence of better fit.
The complete-data expected information in Section 7.5 would treat all nine responses as observed for every person and therefore is not the FIML information. The Hessian above belongs to the observed-data likelihood. It must be positive definite before its inverse is used. The lavaan package fits models by FIML with missing = "ml".
7.8 Computing chi-square, RMSEA, CFI, and SRMR
Fit assessment asks how much likelihood the proposed moment restrictions lose relative to an unrestricted observed distribution. For the complete nine-response sample, let $\ell_{\rm sat}$ be the saturated normal log likelihood and $\ell_{\rm fit}$ the maximized full SEM log likelihood. The saturated estimates are $\bar y$ and $S_n$. With the criterion in Section 7.6,
\[T=2(\ell_{\rm sat}-\ell_{\rm fit})=2n\mathcal F.\]There are nine means and 45 distinct covariance entries, giving 54 observable moments. The full SEM has 30 parameters and, at full local rank, $df=54-30=24$. Setting $c^{\prime}=0$ leaves 29 parameters and $df=25$. An independence model estimates nine means and nine variances, giving $df_0=54-18=36$.
The three free structural paths and three latent disturbance variances can represent an unrestricted positive definite covariance among the three latent variables in this recursive order. The arrows alone therefore add no covariance restriction beyond this full three-factor measurement model. They provide a regression parameterization. Fixing $c^{\prime}=0$ does add a restriction: under the independent structural disturbances, $\xi$ and $\eta_2$ are conditionally independent given $\eta_1$. Their marginal covariance can still be nonzero through $ab$. This is not the same as setting a pair of factors uncorrelated.
Under independent normal sampling, correct specification, local identification, differentiable moments and nonsingular information at an interior true parameter, $T$ has an approximate large-sample chi-square distribution with $df$ degrees of freedom. Optimization convergence concerns a stationary value of the criterion; fit assessment concerns the distance of that optimum from the saturated likelihood. A model can converge well and fit poorly.
The reference chi-square expectation is $df$. The root mean square error of approximation (RMSEA) measures the nonnegative excess discrepancy per person and degree of freedom:
\[\operatorname{RMSEA}=\sqrt{\frac{\max(T-df,0)}{n\,df}},\qquad df>0.\]Truncation makes the result zero whenever $T<df$, so a zero estimate does not establish exact population fit. The denominator here uses the normal likelihood convention with divisor $n$; conventions based on $n-1$ must be matched before comparing values.
Let $\ell_0$ be the independence log likelihood and $T_0=2(\ell_{\rm sat}-\ell_0)$. Its covariance estimate is the diagonal of $S_n$, with free means. The comparative fit index is
\[e=\max(T-df,0),\qquad d=\max(e,T_0-df_0,0),\qquad \operatorname{CFI}=1-\frac e d\quad(d>0).\]Including $e$ in the denominator bounds the fraction by one. If both model and baseline excesses truncate to zero, this ratio is undefined. A high CFI can coexist with a small chi-square tail probability because the two compare discrepancy against different references.
The standardized root mean square residual (SRMR) summarizes sample-to-model moment discrepancies. With $s_j=\sqrt{S_{n,jj}}$,
\[r_{jk}=\frac{S_{n,jk}-\widehat\Sigma_{jk}}{s_js_k},\qquad r_{\mu,j}=\frac{\bar y_j-\widehat\mu_j}{s_j}.\]The covariance-only version averages the squares over all 45 distinct entries, including the diagonal. Including means averages over 54 residuals. Both observed and fitted covariances use the same sample-variance denominator; subtracting separately standardized correlation matrices would hide variance discrepancies. These residuals are differences between sample and fitted moments, distinct from the random disturbances in a person’s structural equations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
sem_indices <- function(loglik, saturated_loglik, baseline_loglik, n, df, baseline_df, S, Sigma,
mean_residual = NULL) {
stopifnot(n > 0, df >= 0, baseline_df >= 0, all(diag(S) > 0), all(dim(S) == dim(Sigma)))
T <- 2 * (saturated_loglik - loglik)
baseline_T <- 2 * (saturated_loglik - baseline_loglik)
stopifnot(T > -1e-6, baseline_T > -1e-6)
T <- max(T, 0)
baseline_T <- max(baseline_T, 0)
excess <- max(T - df, 0)
denominator <- max(excess, baseline_T - baseline_df, 0)
residual <- (S - Sigma) / sqrt(outer(diag(S), diag(S)))
covariance_residuals <- residual[lower.tri(residual, diag = TRUE)]
if (!is.null(mean_residual))
stopifnot(length(mean_residual) == ncol(S), all(is.finite(mean_residual)))
standardized_means <- if (!is.null(mean_residual)) mean_residual / sqrt(diag(S))
list(chisq = T, df = df, pvalue = if (df > 0) pchisq(T, df, lower.tail = FALSE) else NA_real_,
rmsea = if (df > 0) sqrt(excess / (n * df)) else NA_real_,
baseline_chisq = baseline_T, baseline_df = baseline_df,
cfi = if (denominator > 0) 1 - excess / denominator else NA_real_,
srmr = sqrt(mean(c(covariance_residuals, standardized_means)^2)),
srmr_covariance = sqrt(mean(covariance_residuals^2)),
convention = if (is.null(mean_residual)) "normal ML, divisor n, covariance-only SRMR" else
"normal ML, divisor n, SRMR with covariance and mean residuals")
}
In sem_indices(), T and baseline_T are $T$ and $T_0$, excess and denominator are $e$ and $d$, and residual and standardized_means contain $r_{jk}$ and $r_{\mu,j}$. The function returns both SRMR conventions, and returns NA for an undefined CFI denominator or a zero-degree-of-freedom RMSEA. The following comparison fits the restricted structural model to the same people and evaluates both models against the same saturated and independence likelihoods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
saturated_loglik <- -ram_criterion(full_data$mean, full_data$S, full_data)
baseline_loglik <- -ram_criterion(full_data$mean, diag(diag(full_data$S)), full_data)
restricted <- full_sem_spec(direct = FALSE)
restricted_fit <- sem_fit(restricted, full_data, start = ml$theta[restricted$parameters])
indices <- sem_indices(ml$loglik, saturated_loglik, baseline_loglik, nrow(Y),
54 - 30, 54 - 18, full_data$S, ml$model$covariance, full_data$mean - ml$model$mean)
restricted_indices <- sem_indices(restricted_fit$loglik, saturated_loglik,
baseline_loglik, nrow(Y), 54 - 29, 54 - 18, full_data$S,
restricted_fit$model$covariance, full_data$mean - restricted_fit$model$mean)
index_fields <- c("chisq", "df", "pvalue", "rmsea", "cfi", "srmr", "srmr_covariance")
print(rbind(full = unlist(indices[index_fields]),
no_direct_path = unlist(restricted_indices[index_fields])))
difference <- 2 * (ml$loglik - restricted_fit$loglik)
print(c(difference_chisq = difference, difference_df = 1,
pvalue = pchisq(max(difference, 0), 1, lower.tail = FALSE)))
record_check("nested_likelihood_order", max(0, -difference), 1e-5)
1
2
3
4
5
chisq df pvalue rmsea cfi srmr srmr_covariance
full 15.56178 24 0.9032404 0.00000000 1.000000 0.01375797 0.01507110
no_direct_path 30.64541 25 0.2010300 0.02125165 0.996952 0.03376962 0.03699276
difference_chisq difference_df pvalue
1.508363e+01 1.000000e+00 1.028516e-04
The full SEM gives $T=15.5618$ on 24 degrees of freedom, with $p=0.9032$. Because $T<df$, the formulas truncate its RMSEA to zero and its CFI to one. The fitted covariance nevertheless differs from the sample covariance: covariance-only SRMR is $0.01507$. Including the nine nearly zero mean residuals reduces it to $0.01376$, as expected from the factor $\sqrt{45/54}$.
Fixing $c^{\prime}=0$ raises $T$ to $30.6454$ on 25 degrees of freedom, with $p=0.2010$, RMSEA $0.02125$ and CFI $0.99695$. These overall summaries can appear compatible with the restricted model. Yet the additional restriction alone costs $30.6454-15.5618=15.0836$ chi-square units on one degree of freedom, giving $p=0.000103$. The overall test assesses 25 restrictions jointly against a saturated model; the nested comparison isolates the extra restriction within the full SEM. Their different degrees of freedom and alternatives explain why the overall test can be nonsignificant while the one-path comparison is significant.
Thus the high CFI and nonsignificant overall test do not establish that the direct coefficient can be set to zero. The nested comparison provides evidence against that restriction under the specified measurement and disturbance assumptions. It does not test whether every other part of the full SEM is correct or establish a causal interpretation of the retained path.
The formulas above use complete-data saturated moments. An incomplete-data likelihood ratio needs its observed-data saturated reference, and residual-based indices also need a declared missing-data convention. Applying the complete-data sample-covariance formulas to pairwise covariances would silently change the calculation. The lavaan function fitMeasures() reports the chi-square statistic, RMSEA, CFI and SRMR for a fitted model.
7.9 Path and growth models, an empirical full SEM, and numerical comparisons
This section completes the chapter’s examples. It first checks the path-model likelihood by conditional regressions and fits the latent growth model of Section 7.2, then fits a full structural equation model to the observed PoliticalDemocracy data. The last two parts compare the book’s fits with an existing SEM implementation and use repeated samples to assess recovery of the structural coefficients.
Checking the path likelihood by conditional regression
The three-variable path density factors as $p(y_1)p(y_2\mid y_1)p(y_3\mid y_1)$ because its disturbances are independent. The marginal mean and variance of $y_1$ have their normal ML estimates. Each of the remaining equations is an ordinary normal regression on an intercept and $y_1$. Its regression coefficients come from least squares, and its ML disturbance variance is residual sum of squares divided by $n$, rather than $n-2$. These calculations offer a direct reference independent of the RAM moment derivatives. The supplied PATH3 data have one person per row and responses $y_1,y_2,y_3$ in column order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
path_Y <- readRDS(file.path("data/source/ch07/PATH3.rds"))
path_data <- sem_data(path_Y)
X <- cbind(1, path_Y[, 1])
qr_X <- qr(X)
coef2 <- qr.coef(qr_X, path_Y[, 2])
coef3 <- qr.coef(qr_X, path_Y[, 3])
closed_form <- c(coef2[2], coef3[2], path_data$S[1, 1],
mean(qr.resid(qr_X, path_Y[, 2])^2),
mean(qr.resid(qr_X, path_Y[, 3])^2),
mean(path_Y[, 1]), coef2[1], coef3[1])
path_fit <- sem_fit(path, path_data, start = c(.2, .2, diag(path_data$S),
mean(path_Y[, 1]), 0, 0))
print(data.frame(parameter = path$parameters, RAM = unname(path_fit$theta),
conditional_regression = unname(closed_form)), row.names = FALSE)
path_gap <- max(abs(path_fit$theta - closed_form))
print(c(parameter_gap = path_gap))
record_check("path_conditional_regression", path_gap, 2e-4)
The two columns of X are the constant and observed predictor, so coef2[2] and coef3[2] supply the path coefficients. The vector closed_form then follows path$parameters: two slopes, three disturbance variances and three structural intercepts. Its values appear in the conditional_regression column below.
1
2
3
4
5
6
7
8
9
10
11
parameter RAM conditional_regression
a21 0.58081346 0.58081346
a31 0.40638455 0.40638455
variance1 1.05869332 1.05869332
variance2 0.49126467 0.49126467
variance3 0.70767575 0.70767576
intercept1 0.99299543 0.99299543
intercept2 0.13959841 0.13959841
intercept3 -0.09108612 -0.09108612
parameter_gap
3.666269e-09
The fitted slopes are $0.58081$ and $0.40638$, and the largest parameter discrepancy between the two calculations is $3.67\times10^{-9}$. Agreement checks the array orientation, the distinction between structural intercepts and response means, and the likelihood’s variance divisor. This example serves a different purpose from the latent full SEM: its predictors are observed without a measurement model, so conditional regressions solve the joint likelihood directly.
Estimating and interpreting the latent growth model
The growth model introduced in Section 7.2 is fitted to the four responses of each of 200 people. The sample size in its normal likelihood is 200, not the 800 rows of the long representation. The common residual variance and five other parameters are estimated in the six-dimensional space defined by growth_K. The starting mean slope is the difference between last and first sample means divided by the elapsed time of three units. After fitting, the calculation reconstructs $G$, $Z\hat\beta$ and $Z\widehat G Z^\top+\hat\psi I_4$ directly from the reported parameters and evaluates each person’s normal density. This provides a second evaluation of the fitted marginal likelihood.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
growth_data <- sem_data(wide)
growth_start <- c(rep(.5, 4), 1, 0, .25, mean(wide[, 1]),
(mean(wide[, 4]) - mean(wide[, 1])) / 3)
growth_fit <- sem_fit(growth, growth_data, start = growth_start, K = growth_K)
growth_parameters <- c(1, 5:9)
print(data.frame(parameter = c("common_residual", growth$parameters[5:9]),
estimate = unname(growth_fit$theta[growth_parameters]),
SE = growth_fit$information$se[growth_parameters]), row.names = FALSE)
growth_G <- matrix(growth_fit$theta[c(5, 6, 6, 7)], 2)
growth_mean <- drop(Z_time %*% growth_fit$theta[8:9])
growth_covariance <- Z_time %*% growth_G %*% t(Z_time) + diag(growth_fit$theta[1], 4)
growth_loglik <- sum(normal_contributions(wide, growth_mean, growth_covariance))
growth_mean_residual <- growth_data$mean - growth_mean
print(data.frame(time = 0:3, sample_mean = growth_data$mean,
fitted_mean = growth_mean, mean_residual = growth_mean_residual))
print(c(intercept_slope_correlation = growth_G[1, 2] / sqrt(prod(diag(growth_G))),
restricted_information_rank = growth_fit$information$rank,
loglik_identity_gap = abs(growth_fit$loglik - growth_loglik),
mean_penalty = nrow(wide) / 2 * drop(crossprod(growth_mean_residual,
solve(growth_covariance, growth_mean_residual)))))
growth_indices <- sem_indices(growth_fit$loglik,
-ram_criterion(growth_data$mean, growth_data$S, growth_data),
-ram_criterion(growth_data$mean, diag(diag(growth_data$S)), growth_data),
nrow(wide), 14 - 6, 14 - 8, growth_data$S, growth_fit$model$covariance,
growth_data$mean - growth_fit$model$mean)
print(unlist(growth_indices[index_fields]))
record_check("growth_LMM_marginal_likelihood", abs(growth_fit$loglik - growth_loglik), 1e-8)
record_check("growth_fit_converged", as.numeric(!growth_fit$optimizer$converged), 0)
saveRDS(growth_fit, file.path("data/derived/ch07", "growth-fit.rds"))
The selection growth_parameters = c(1, 5:9) reports one copy of the common error variance and the five remaining parameters. The indices c(5, 6, 6, 7) reconstruct both symmetric positions of $G$ from its three stored entries.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
parameter estimate SE
common_residual 0.4790511 0.03387403
G11 1.1451694 0.14993734
G21 0.1201136 0.05380968
G22 0.2810106 0.03828625
mean_intercept 2.0745469 0.08603793
mean_slope 0.4014797 0.04340627
time sample_mean fitted_mean mean_residual
y1 0 2.101567 2.074547 0.027020465
y2 1 2.428302 2.476027 -0.047724261
y3 2 2.891893 2.877506 0.014387177
y4 3 3.285303 3.278986 0.006316661
intercept_slope_correlation restricted_information_rank loglik_identity_gap
2.117366e-01 6.000000e+00 4.547474e-13
mean_penalty
6.793850e-01
chisq df pvalue rmsea cfi srmr
7.28190114 8.00000000 0.50654555 0.00000000 1.00000000 0.01810632
srmr_covariance
0.01734610
The estimated population trajectory is $\widehat E(y_{it})=2.0745+0.4015t$. The mean intercept has SE $0.0860$ and the mean slope has SE $0.0434$. Thus the fitted average response rises by about $0.4015$ response units per time unit. This is the population mean slope, not an estimate that every person follows exactly.
The estimated intercept variance, G11, is $1.1452$, and the slope variance, G22, is $0.2810$. They describe differences among people’s latent trajectories. The positive mean slope does not require every person’s latent slope to be positive. The covariance G21 is $0.1201$, giving an intercept-slope correlation of $0.2117$: under the fitted model, higher latent starting levels are associated with larger slopes. The common occasion error variance is $0.4791$, describing variation around each person’s latent line rather than variation in those lines themselves.
The standard errors in the table describe uncertainty in these six population parameters. For example, $0.2810$ is the estimated variance of individual slopes, whereas its SE, $0.0383$, describes sampling uncertainty in that variance estimate. The restricted moment-Jacobian rank is six. Standard errors are obtained by inverting information in the free coordinates and mapping back with $K$. In particular, because $\psi=z_1/2$, the sampling variance of $\hat\psi$ is one quarter of that of $\hat z_1$. There are not four independently estimated residual variances simply because the stored parameter vector contains four copies.
Four unrestricted sample means generally do not fall exactly on a line. The fitted means $\hat\beta_0+t\hat\beta_1$ impose that linear restriction. The reported mean penalty
\[\frac n2(\bar y-Z\hat\beta)^\top\widehat\Sigma^{-1}(\bar y-Z\hat\beta)\]equals $0.6794$ in this fit. For example, the sample mean at time one is $2.4283$, while the fitted line gives $2.4760$, leaving a mean residual of $-0.04772$. Giving each occasion a free mean would remove the linear-mean restriction and change the model.
The combined mean and covariance test gives $T=7.2819$ on eight degrees of freedom, with $p=0.5065$, RMSEA zero and CFI one. Mean-and-covariance SRMR is $0.01811$, slightly larger than its covariance-only value of $0.01735$. Here the nonzero mean residuals contribute to the summary; including means does not produce the simple reduction seen in the full SEM with nine freely fitted response means.
The same probability model can be written as a linear mixed model with random intercept $b_{0i}$ and random slope $b_{1i}$:
\[y_i=Z\beta+Zb_i+e_i,\qquad b_i\sim N(0,G),\qquad e_i\sim N(0,\psi I_4).\]Integrating the random effects gives $N(Z\beta,ZGZ^\top+\psi I_4)$, exactly the RAM marginal distribution. The growth_loglik calculation evaluates this distribution directly for every person and differs from the fitted RAM log likelihood by $4.55\times10^{-13}$. This checks the marginal likelihood and parameter mapping without requiring a mixed-model package. The comparison is ML with ML: restricted maximum likelihood changes the variance-component criterion and cannot be compared as though it were this same full normal likelihood. A different residual-correlation structure or heterogeneous occasion variances would likewise define a different model.
A positive estimated slope variance indicates variation in trajectories under the model, but an ordinary symmetric interval can extend below zero. Testing the null of no random slope places a variance on the boundary and also constrains its covariance with the intercept. The interior chi-square argument in Section 7.8 does not apply unchanged. This boundary issue is separate from deciding whether the mean trajectory is linear.
The growth representation is a constrained latent-variable model whose intercept and slope factors summarize repeated observations. It does not require arrows between those two factors. The full SEM developed earlier instead combines a freely estimated measurement model with regressions among its factors. Both use the same RAM likelihood, but their fixed coefficients and mean restrictions express different scientific questions.
Industrialization and political democracy
The models so far were fitted to simulated responses. The observed PoliticalDemocracy data distributed with lavaan contain 75 country records and 11 measures of industrialization and democracy. Three variables describe industrialization in 1960, and four democracy measures appear in each of 1960 and 1965. The dataset documentation and the package’s SEM tutorial identify the variables and the example model. The reported run used R 4.5.2 and lavaan 0.7-3.
| Latent variable | Observed variables | Content |
|---|---|---|
| Industrialization, 1960 | x1–x3 | GNP per capita, energy consumption per capita, industrial labor-force share |
| Democracy, 1960 | y1–y4 | Press, opposition, elections, legislature |
| Democracy, 1965 | y5–y8 | The corresponding four democracy measures |
All coefficients below use the numerical scales in the distributed data. The marker variables x1, y1 and y5 define the three factor scales. Let $\xi$ denote industrialization in 1960, $\eta_1$ democracy in 1960, and $\eta_2$ democracy in 1965. The structural equations are again
Thus $b$ describes the association of later democracy with earlier democracy at a given industrialization level. The indirect path $ab$ passes through democracy in 1960, whereas $c^{\prime}$ is the remaining industrialization coefficient at a given earlier-democracy value. The temporal ordering of the democracy measures does not by itself justify a causal interpretation, especially for the relationship between two constructs measured in 1960.
Unlike the simulation, this application allows six covariances between response errors: $(y_1,y_5)$, $(y_2,y_4)$, $(y_2,y_6)$, $(y_3,y_7)$, $(y_4,y_8)$ and $(y_6,y_8)$. Four link the same measure across years; two link measures within a year. They represent residual association beyond the factors. The structural disturbances remain mutually uncorrelated. Adding these entries changes the measurement assumptions and requires checking the whole disturbance covariance, rather than only its diagonal.
The primary empirical model estimates the nonmarker democracy loadings separately by year. A second model equates the corresponding three pairs. Those equality constraints assess whether the two measurement systems can use the same loading coefficients under the selected marker scales. They do not equate all response intercepts, and therefore do not establish scalar measurement invariance or identify a comparison of latent democracy means. Factor means remain zero and all eleven observed means are free in both fits.
Order the RAM variables as x1–x3, y1–y8, followed by industrialization, democracy in 1960 and democracy in 1965. The arrays therefore have dimension 14. The marker responses occupy rows one, four and eight, and their factors occupy columns twelve, thirteen and fourteen. The following constructor uses this order for both measurement and structural assignments.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
political_spec <- function(equal_loadings = FALSE, direct = TRUE) {
A <- matrix(0, 14, 14)
A[cbind(c(1, 4, 8), 12:14)] <- 1
loading_rows <- c(2, 3, 5, 6, 7, 9, 10, 11)
loading_names <- paste0("loading", loading_rows)
if (equal_loadings) loading_names[6:8] <- loading_names[3:5]
residual_rows <- c(8, 7, 9, 10, 11, 11)
residual_cols <- c(4, 5, 5, 6, 7, 9)
parameter_table <- data.frame(
matrix = c(rep("A", 11), rep("S", 20), rep("m", 11)),
row = c(loading_rows, 13, 14, 14, 1:14, residual_rows, 1:11),
col = c(12, 12, rep(13, 3), rep(14, 3), 12, 13, 12,
1:14, residual_cols, rep(1, 11)),
parameter = c(loading_names, "a", "b", "cprime", paste0("residual", 1:11),
"phi", "psi1", "psi2", paste0("error_cov", 1:6),
paste0("intercept", 1:11)))
if (!direct) parameter_table <- parameter_table[parameter_table$parameter != "cprime", ]
parameters <- unique(parameter_table$parameter)
ram_spec(A, diag(14), rep(0, 14), cbind(diag(11), matrix(0, 11, 3)),
parameter_table, setNames(rep("identity", length(parameters)), parameters))
}
For example, error_cov1 occupies $S_{8,4}$, the covariance between errors for y5 and y1; ram_expand() supplies its symmetric counterpart. Under equal loadings, the entry for y6 in row nine receives the same name, loading5, as the entry for y2 in row five. The other two corresponding pairs share names in the same way. Taking the unique parameter names gives one coordinate per shared coefficient while retaining both assignments in the table. Removing the cprime assignment fixes its initially zero path entry, as in the simulated SEM.
The data columns are then selected in this same observed order. Their printed standard deviations use the divisor-$n$ covariance stored by sem_data().
1
2
3
4
5
6
7
8
9
10
11
12
political <- political_spec()
political_equal <- political_spec(equal_loadings = TRUE)
data("PoliticalDemocracy", package = "lavaan", envir = environment())
political_names <- c(paste0("x", 1:3), paste0("y", 1:8))
political_Y <- as.matrix(PoliticalDemocracy[, political_names])
stopifnot(identical(dim(political_Y), c(75L, 11L)), !anyNA(political_Y))
political_data <- sem_data(political_Y)
saveRDS(political_Y, file.path("data/source/ch07", "PoliticalDemocracy.rds"))
print(data.frame(variable = political_names, mean = political_data$mean,
SD = sqrt(diag(political_data$S))), row.names = FALSE)
print(c(free_loading_parameters = length(political$parameters),
equal_loading_parameters = length(political_equal$parameters)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
variable mean SD
x1 5.054384 0.7280019
x2 4.792195 1.5005595
x3 3.557690 1.3963084
y1 5.464667 2.6051586
y2 4.256443 3.9207251
y3 6.563110 3.2589452
y4 4.452533 3.3270627
y5 5.136252 2.5951264
y6 2.978074 3.3501722
y7 6.196264 3.2642580
y8 4.043390 3.2238828
free_loading_parameters equal_loading_parameters
42 39
The free-loading model has eight loadings, three structural coefficients, fourteen diagonal disturbance variances, six disturbance covariances and eleven observed intercepts: 42 parameters. Its 77 observable moments give 35 degrees of freedom at full local rank. Equalizing the three loading pairs reduces the count to 39 and adds three degrees of freedom. The two printed parameter counts refer to the entire models, including their variance and mean parameters. The free-loading specification follows the tutorial’s covariance model with an explicitly fitted mean structure; its published output is not imported into this chapter.
The starting rule below uses each marker’s sample variance, cross-covariances within each measurement group, and sample means. Covariance starts are zero. Shared loadings receive the average of the relevant initial coefficients so that an equality-constrained start satisfies its constraints from the outset.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
political_start <- function(data, spec) {
start <- setNames(numeric(length(spec$parameters)), spec$parameters)
groups <- list(1:3, 4:7, 8:11)
variance_names <- c("phi", "psi1", "psi2")
loadings <- numeric(11)
variances <- numeric(3)
for (g in seq_along(groups)) {
rows <- groups[[g]]
marker <- rows[1]
variances[g] <- .5 * data$S[marker, marker]
loadings[marker] <- 1
loadings[rows[-1]] <- data$S[marker, rows[-1]] / variances[g]
bound <- sqrt(.9 * diag(data$S)[rows[-1]] / variances[g])
loadings[rows[-1]] <- pmin(pmax(loadings[rows[-1]], -bound), bound)
}
table <- spec$parameter_table
loading_table <- table[table$matrix == "A" & table$row <= 11, ]
for (parameter in unique(loading_table$parameter)) {
rows <- loading_table$row[loading_table$parameter == parameter]
start[parameter] <- mean(loadings[rows])
}
start[paste0("residual", 1:11)] <- .5 * diag(data$S)
start[variance_names] <- variances
start[paste0("intercept", 1:11)] <- data$mean
start
}
The returned vector follows spec$parameters. For a shared loading such as loading5, the lookup retrieves both relevant response rows and assigns their average initial coefficient to the single coordinate. The variance names phi, psi1 and psi2 receive the three positive factor-variance starts. Structural coefficients and error covariances remain at their initialized zeros. As in the simulated example, these choices concern the starting point; they do not fix the corresponding parameters during estimation.
The empirical fit uses two starts, differing in their structural coefficients. Both begin with a positive diagonal disturbance covariance. The comparison records their likelihoods, gradients and smallest disturbance eigenvalues. A converged, admissible result with a sufficiently small gradient is selected by likelihood; if no such result is available, execution stops with the diagnostics retained. This selection addresses the numerical search and does not establish a global maximum.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
political_initial <- political_start(political_data, political)
political_alternative <- political_initial
political_alternative[c("a", "b", "cprime")] <- c(.5, .5, .1)
political_candidates <- lapply(list(independent_start = political_initial,
positive_paths_start = political_alternative), function(start) {
tryCatch(sem_fit(political, political_data, start = start), error = function(e) e)
})
political_candidate_table <- do.call(rbind, lapply(political_candidates, function(fit) {
if (inherits(fit, "error")) return(data.frame(nll = NA_real_, converged = FALSE,
gradient_per_country = NA_real_, smallest_disturbance_eigenvalue = NA_real_))
data.frame(nll = fit$value, converged = fit$optimizer$converged,
gradient_per_country = max(abs(fit$gradient)) / political_data$n,
smallest_disturbance_eigenvalue = fit$admissibility$smallest_disturbance_eigenvalue)
}))
print(political_candidate_table)
usable <- with(political_candidate_table, converged & is.finite(nll) &
gradient_per_country < 2e-5 & smallest_disturbance_eigenvalue > -1e-8)
usable[is.na(usable)] <- FALSE
if (!any(usable)) stop("No admissible, converged PoliticalDemocracy fit; inspect the saved log.")
selected <- which(usable)[which.min(political_candidate_table$nll[usable])]
political_fit <- political_candidates[[selected]]
political_equal_fit <- sem_fit(political_equal, political_data,
start = political_start(political_data, political_equal))
political_restricted <- political_spec(direct = FALSE)
political_restricted_fit <- sem_fit(political_restricted, political_data,
start = political_fit$theta[political_restricted$parameters])
political_sat <- -ram_criterion(political_data$mean, political_data$S, political_data)
political_base <- -ram_criterion(political_data$mean, diag(diag(political_data$S)), political_data)
political_indices <- sem_indices(political_fit$loglik, political_sat, political_base,
75, 77 - 42, 77 - 22, political_data$S, political_fit$model$covariance,
political_data$mean - political_fit$model$mean)
print(data.frame(parameter = political$parameters, estimate = unname(political_fit$theta),
SE = political_fit$information$se), row.names = FALSE)
print(structural_effects(political_fit$theta, political_fit$information$covariance),
row.names = FALSE)
print(unlist(political_indices[index_fields]))
political_tests <- data.frame(restriction = c("equal democracy loadings", "no direct path"),
difference_chisq = 2 * c(political_fit$loglik - political_equal_fit$loglik,
political_fit$loglik - political_restricted_fit$loglik),
difference_df = c(3, 1),
converged = c(political_equal_fit$optimizer$converged,
political_restricted_fit$optimizer$converged))
political_tests$pvalue <- pchisq(pmax(political_tests$difference_chisq, 0),
political_tests$difference_df, lower.tail = FALSE)
print(political_tests, row.names = FALSE)
record_check("political_nested_fit_convergence", sum(!political_tests$converged), 0)
record_check("political_nested_likelihood_order", max(0, -political_tests$difference_chisq), 1e-5)
saveRDS(list(free = political_fit, equal_loadings = political_equal_fit,
no_direct = political_restricted_fit, candidates = political_candidate_table),
file.path("data/derived/ch07", "political-fits.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
nll converged gradient_per_country smallest_disturbance_eigenvalue
independent_start 1547.791 TRUE 8.665329e-07 0.08154937
positive_paths_start 1547.791 TRUE 2.343887e-07 0.08154938
parameter estimate SE
loading2 2.18036770 0.13850927
loading3 1.81851115 0.15195812
loading5 1.25674625 0.18243967
loading6 1.05771641 0.15138326
loading7 1.26478652 0.14500626
loading9 1.18569707 0.16881056
loading10 1.27951259 0.15990178
loading11 1.26594789 0.15811129
a 1.48299942 0.39914853
b 0.83734435 0.09835095
cprime 0.57233673 0.22131368
residual1 0.08154938 0.01948974
residual2 0.11980641 0.06972065
residual3 0.46670269 0.09015651
residual4 1.89139542 0.44442383
residual5 7.37286825 1.37389261
residual6 5.06746915 0.95172813
residual7 3.14790440 0.73878422
residual8 2.35097167 0.48023869
residual9 4.95396395 0.91424633
residual10 3.43137500 0.71284349
residual11 3.25408245 0.69460405
phi 0.44843723 0.08669173
psi1 3.95603210 0.92118457
psi2 0.17248127 0.21480442
error_cov1 0.62367177 0.35832027
error_cov2 1.31311442 0.70198343
error_cov3 2.15285979 0.73377563
error_cov4 0.79496305 0.60769845
error_cov5 0.34822408 0.44223996
error_cov6 1.35616475 0.56828592
intercept1 5.05438384 0.08406241
intercept2 4.79219463 0.17326967
intercept3 3.55768979 0.16123179
intercept4 5.46466667 0.30185360
intercept5 4.25644288 0.44987037
intercept6 6.56311025 0.37588487
intercept7 4.45253304 0.38390947
intercept8 5.13625192 0.30051123
intercept9 2.97807408 0.38593314
intercept10 6.19626389 0.37719933
intercept11 4.04338968 0.37132145
effect estimate SE lower upper
direct 0.5723367 0.2213137 0.1385699 1.006104
indirect 1.2417812 0.3554221 0.5451667 1.938396
total 1.8141179 0.3735882 1.0818985 2.546337
chisq df pvalue rmsea cfi srmr
38.12521823 35.00000000 0.32918035 0.03450448 0.99537453 0.04112265
srmr_covariance
0.04441754
restriction difference_chisq difference_df converged pvalue
equal democracy loadings 2.054271 3 TRUE 0.56121925
no direct path 5.995278 1 TRUE 0.01434422
Both starts converge to a negative log likelihood of $1547.791$ at the printed precision. Their maximum gradients per country are below $10^{-6}$, and their smallest disturbance eigenvalues are about $0.08155$. The selected free-loading fit therefore has a positive definite disturbance covariance as well as a numerically small gradient.
The estimated coefficient from industrialization to democracy in 1960 is $\hat a=1.4830$ with SE $0.3991$. The coefficient from democracy in 1960 to democracy in 1965 is $\hat b=0.8373$ with SE $0.0984$, at a given industrialization level. The remaining direct coefficient from industrialization to democracy in 1965 is $\hat c^{\prime}=0.5723$ with SE $0.2213$, at a given earlier-democracy value. These are unstandardized coefficients: $a$ uses 1960-democracy factor units per industrialization unit, and $b$ uses 1965-democracy units per 1960-democracy unit.
The indirect coefficient is $\hat a\hat b=1.2418$ with SE $0.3554$ and a 95% normal interval from $0.5452$ to $1.9384$. The total is $1.8141$ with SE $0.3736$ and interval from $1.0819$ to $2.5463$. Both the indirect and direct coefficients have 1965-democracy units per industrialization unit, so they can be added. Their positive intervals summarize the modeled associations under the chosen measurement and disturbance assumptions; they do not independently establish causal effects.
The error variances and covariances describe measurement variation left after the factors. By contrast, $\hat\psi_1=3.9560$ and $\hat\psi_2=0.1725$ describe variation left after the structural regressions. The latter variance has SE $0.2148$, larger than its estimate. Although the fitted value is positive, this uncertainty makes a symmetric normal interval for that variance a poor description of its admissible range.
The free-loading model gives $T=38.1252$ on 35 degrees of freedom, with $p=0.3292$, RMSEA $0.03450$, CFI $0.99537$ and mean-and-covariance SRMR $0.04112$. These summaries describe its overall moment discrepancies. The two nested comparisons then isolate particular restrictions within that model.
Equating the three corresponding democracy-loading pairs costs $2.0543$ chi-square units on three degrees of freedom, with $p=0.5612$. The data do not provide evidence against these loading equalities in this comparison; the result neither proves equality nor adds the intercept constraints needed for scalar measurement invariance. Fixing the direct path at zero instead costs $5.9953$ on one degree of freedom, with $p=0.0143$. That comparison provides evidence against removing the direct coefficient under the stated model. It is distinct from the test of loading equality and from the overall fit test.
Both nested optimizers report convergence. Interpretation of their chi-square comparisons requires the regularity and admissibility conditions described earlier. The small sample, coarse or nonnormal ratings, and possible dependence among countries can limit ordinary normal-theory approximations. The present calculation treats countries as independent and indicators as continuous normal measurements, so the reported uncertainty and test probabilities refer to that working model.
This application adds observed-data interpretation to the simulation’s numerical checks. It does not use the data to select residual covariances automatically after inspecting fit. The specified residual structure and the two declared restrictions define the models before estimation.
Comparisons with an existing SEM implementation
A useful comparison must align model constraints, response order, marker scaling, mean structure, likelihood divisor and information convention. For the full SEM the three marker loadings are one and all three latent disturbance variances are free. For growth, the occasion loadings and zero observed intercepts are fixed, both latent means are free, and four error variances share one value. The empirical comparison uses the same six residual covariances and separately checks its cross-year loading constraints.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
full_syntax <- "
xi =~ 1*y1 + loading2*y2 + loading3*y3
eta1 =~ 1*y4 + loading5*y5 + loading6*y6
eta2 =~ 1*y7 + loading8*y8 + loading9*y9
eta1 ~ a*xi
eta2 ~ b*eta1 + cprime*xi
xi ~~ 0*eta1 + 0*eta2
eta1 ~~ 0*eta2
"
growth_syntax <- "
i =~ 1*y1 + 1*y2 + 1*y3 + 1*y4
s =~ 0*y1 + 1*y2 + 2*y3 + 3*y4
y1 ~~ residual*y1
y2 ~~ residual*y2
y3 ~~ residual*y3
y4 ~~ residual*y4
"
In these model strings, =~ introduces a factor’s measurement equation, ~ introduces a regression, and ~~ specifies a variance or covariance. A numeric multiplier fixes a coefficient; a name labels a free coefficient. Thus xi =~ 1*y1 + loading2*y2 + loading3*y3 uses the same marker and loading labels as the first measurement block. In the growth string, repeating residual imposes the common error variance across all four occasions. A covariance between two endogenous or exogenous latent variables in this syntax concerns the random terms remaining after their specified regressions, so the fixed zeros express the structural-disturbance assumptions.
For the empirical comparison, the next helper constructs measurement labels and error covariances from the RAM table. It is used for the free-loading and equal-loading specifications below, both of which retain all three structural paths.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Construct the real-data syntax directly from the documented RAM locations.
# This preserves free loading names and all six residual-covariance positions.
political_syntax_from_ram <- function(spec) {
observed <- c(paste0("x", 1:3), paste0("y", 1:8))
latent <- c("ind60", "dem60", "dem65")
table <- spec$parameter_table
lines <- character()
groups <- list(1:3, 4:7, 8:11)
for (g in seq_along(groups)) {
rows <- groups[[g]]
free <- table[table$matrix == "A" & table$row %in% rows[-1], ]
terms <- c(paste0("1*", observed[rows[1]]),
paste0(free$parameter, "*", observed[free$row]))
lines <- c(lines, paste(latent[g], "=~", paste(terms, collapse = " + ")))
}
lines <- c(lines, "dem60 ~ a*ind60", "dem65 ~ b*dem60 + cprime*ind60",
"ind60 ~~ 0*dem60 + 0*dem65", "dem60 ~~ 0*dem65")
residual <- table[table$matrix == "S" & table$row != table$col, ]
for (j in seq_len(nrow(residual))) {
lines <- c(lines, paste(observed[residual$row[j]], "~~",
paste0(residual$parameter[j], "*", observed[residual$col[j]])))
}
paste(lines, collapse = "\n")
}
For each measurement group, terms starts with the fixed marker and adds the parameter labels at the remaining response rows. A repeated RAM label therefore becomes a repeated label in the model string. For instance, loading5 labels both y2 and y6 in the equal-loading model. The off-diagonal S entries supply error-covariance statements: $S_{8,4}$ becomes y5 ~~ error_cov1*y1. Joining lines with newlines returns one model string accepted by the fitting function. This translation makes the matched constraints explicit; it does not translate arbitrary RAM specifications.
1
2
3
4
5
6
7
8
9
10
11
12
13
reference_full <- lavaan::sem(full_syntax, data = as.data.frame(Y),
std.lv = FALSE, meanstructure = TRUE, likelihood = "normal", information = "expected")
reference_missing <- lavaan::sem(full_syntax, data = as.data.frame(Y_missing),
std.lv = FALSE, meanstructure = TRUE, likelihood = "normal",
missing = "ML", information = "observed")
reference_growth <- lavaan::growth(growth_syntax, data = as.data.frame(wide),
likelihood = "normal", information = "expected")
reference_political <- lavaan::sem(political_syntax_from_ram(political),
data = as.data.frame(political_Y), std.lv = FALSE, meanstructure = TRUE,
likelihood = "normal", information = "expected")
reference_political_equal <- lavaan::sem(political_syntax_from_ram(political_equal),
data = as.data.frame(political_Y), std.lv = FALSE, meanstructure = TRUE,
likelihood = "normal", information = "expected")
Complete-data fits request expected information; FIML requests observed information. All use normal ML with the mean structure stated explicitly. lavaan::growth() supplies the growth-model mean defaults, whereas the SEM calls fix latent means and estimate observed intercepts. The following helper matches parameters by their equation roles instead of assuming that package and RAM vectors have the same order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
reference_parameters <- function(reference, spec, observed, latent, column = "est") {
estimates <- lavaan::parameterEstimates(reference)
variables <- c(observed, latent)
vapply(spec$parameters, function(parameter) {
positions <- spec$parameter_table[spec$parameter_table$parameter == parameter, ]
position <- positions[1, ]
row <- variables[position$row]
col <- variables[position$col]
if (position$matrix == "m") {
selected <- estimates$op == "~1" & estimates$lhs == row
} else if (position$matrix == "S") {
selected <- estimates$op == "~~" & ((estimates$lhs == row & estimates$rhs == col) |
(estimates$lhs == col & estimates$rhs == row))
} else if (position$row <= length(observed) && position$col > length(observed)) {
selected <- estimates$op == "=~" & estimates$lhs == col & estimates$rhs == row
} else {
selected <- estimates$op == "~" & estimates$lhs == row & estimates$rhs == col
}
value <- estimates[[column]][selected]
stopifnot(length(value) == 1L)
value
}, 0.0)
}
The package table identifies each parameter by an operator op and the variable names on its left and right, lhs and rhs. The helper returns one value per entry of spec$parameters, extracting either the estimate column est or the standard-error column se. The combined variables vector must follow the RAM order: observed variables first, then latent variables.
An entry of $m$ matches an intercept or mean row with operator ~1. An entry of $S$ matches ~~, allowing either order of the two variable names because a covariance is symmetric. For a loading, RAM puts the response in the row and factor in the column, while the measurement syntax puts the factor to the left of =~. Consequently loading2 in the simulated model, at $A_{2,10}$, matches xi =~ y2. A structural path preserves the outcome-predictor order: b at $A_{12,11}$ matches eta2 ~ eta1.
When a parameter has repeated locations, positions[1, ] selects one representative. This is valid for the comparisons here because both specifications impose the same equality label: the shared locations have the same estimate and standard error. The length check requires exactly one matching package row for that representative. Matching equation roles this way prevents a difference in table order from appearing as a parameter discrepancy.
1
2
3
4
5
6
7
8
9
10
11
compare_reference <- function(ours, reference, observed, latent, our_se) {
fitted <- lavaan::fitted(reference)
reference_theta <- reference_parameters(reference, ours$spec, observed, latent)
reference_se <- reference_parameters(reference, ours$spec, observed, latent, "se")
c(parameter_gap = max(abs(ours$theta - reference_theta)),
mean_gap = max(abs(ours$model$mean - fitted$mean[observed])),
covariance_gap = max(abs(ours$model$covariance - fitted$cov[observed, observed])),
loglik_gap = abs(ours$loglik - as.numeric(lavaan::fitMeasures(reference, "logl"))),
SE_gap = max(abs(our_se - reference_se)),
reference_converged = as.numeric(lavaan::lavInspect(reference, "converged")))
}
The comparison aligns both the parameter vector and the fitted moments before subtracting them. Its parameter, mean, covariance and SE fields are maximum absolute discrepancies on the matched original scales; loglik_gap is the absolute difference between full log likelihoods. our_se must follow the RAM parameter order, with the observed-information standard errors supplied for FIML. The separate convergence field records whether the reference search succeeded. The calls below apply these checks to each fitted case and then compare the complete full SEM’s fit indices using the same conventions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
reference_table <- rbind(
FULLSEM9 = compare_reference(ml, reference_full, colnames(Y), c("xi", "eta1", "eta2"),
ml$information$se),
FULLSEM9_FIML = compare_reference(missing_fit, reference_missing, colnames(Y),
c("xi", "eta1", "eta2"), missing_se),
GROWTH4 = compare_reference(growth_fit, reference_growth, colnames(wide), c("i", "s"),
growth_fit$information$se),
PoliticalDemocracy = compare_reference(political_fit, reference_political, political_names,
c("ind60", "dem60", "dem65"), political_fit$information$se),
PoliticalDemocracy_equal = compare_reference(political_equal_fit, reference_political_equal,
political_names, c("ind60", "dem60", "dem65"), political_equal_fit$information$se))
print(reference_table)
for (case in rownames(reference_table)) {
for (quantity in c("parameter_gap", "mean_gap", "covariance_gap", "loglik_gap", "SE_gap")) {
tolerance <- if (quantity == "loglik_gap") 2e-5 else if (quantity == "SE_gap") 3e-3 else 1e-3
record_check(paste(case, quantity, sep = "_"), reference_table[case, quantity], tolerance)
}
record_check(paste0(case, "_reference_converged"),
1 - reference_table[case, "reference_converged"], 0)
}
reference_index_table <- rbind(
ours = unlist(indices[c("chisq", "df", "rmsea", "cfi", "srmr")]),
lavaan = as.numeric(lavaan::fitMeasures(reference_full, c("chisq", "df", "rmsea", "cfi", "srmr"))))
print(reference_index_table)
record_check("full_SEM_fit_indices", max(abs(reference_index_table[1, ] -
reference_index_table[2, ])), 2e-4)
saveRDS(list(full = reference_full, missing = reference_missing, growth = reference_growth,
political = reference_political, political_equal = reference_political_equal,
comparison = reference_table), file.path("data/derived/ch07", "references.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
parameter_gap mean_gap covariance_gap loglik_gap SE_gap
FULLSEM9 1.128751e-07 0.000000e+00 7.352651e-08 7.275958e-12 4.665180e-09
FULLSEM9_FIML 5.140345e-07 5.140345e-07 2.471534e-07 1.045919e-10 2.498994e-08
GROWTH4 7.650457e-09 6.776986e-09 2.147951e-08 4.547474e-13 3.593114e-10
PoliticalDemocracy 7.054616e-06 0.000000e+00 7.075204e-06 6.730261e-11 1.045984e-06
PoliticalDemocracy_equal 1.214706e-04 0.000000e+00 9.046001e-05 2.055617e-08 1.300541e-05
reference_converged
FULLSEM9 1
FULLSEM9_FIML 1
GROWTH4 1
PoliticalDemocracy 1
PoliticalDemocracy_equal 1
chisq df rmsea cfi srmr
ours 15.56178 24 0 1 0.01375797
lavaan 15.56178 24 0 1 0.01375796
The complete simulated SEM agrees with lavaan to about $1.13\times10^{-7}$ in parameters and $7.28\times10^{-12}$ in log likelihood. The FIML parameter discrepancy is $5.14\times10^{-7}$, and its observed-information standard errors differ by at most $2.50\times10^{-8}$. For growth, the largest parameter discrepancy is $7.65\times10^{-9}$.
The empirical free-loading model has a parameter discrepancy of $7.05\times10^{-6}$. The equality-constrained model has the largest discrepancy in the table, $1.21\times10^{-4}$, while its log likelihood discrepancy is only $2.06\times10^{-8}$ and its largest SE discrepancy is $1.30\times10^{-5}$. These values are within the declared numerical tolerances. A close likelihood does not require identical parameter digits because convergence tolerances and curvature affect the location of the final numerical point.
The separate index comparison reproduces the full SEM’s chi-square, degrees of freedom, RMSEA and CFI at the printed precision. SRMR differs only in the last displayed digit, consistent with the small fitted-moment differences. This comparison also checks the stated residual convention.
The book’s default optimizer is translated from the PORT routines underlying nlminb(), with some controls adapted from lavaan. Agreement with the package consequently checks translation and model specification; it is not evidence from wholly independent optimization algorithms. The conditional-regression path solution, the reduced-equation moment identities, the direct growth likelihood and numerical derivative checks supply complementary references.
Repeated-sample recovery of structural coefficients
The single simulated fit cannot measure bias or interval coverage. Repeated samples from the same full SEM provide that assessment. Each replication generates 500 response vectors from the known marginal normal moments, constructs data-based starts, and fits the same model. This generation is equivalent in distribution to drawing factors and response errors separately, but estimation again receives only the responses. The setup defines replications from the environment variable STAT_BOOK_SEM_REPLICATIONS, with a default of 200 for the results reported here. It is the number of independently generated samples, distinct from the 500 people within each sample.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
set.seed(70703)
replication_seeds <- sample.int(.Machine$integer.max, replications)
parameter_names <- c("a", "b", "cprime")
recovery <- vector("list", replications)
for (replication in seq_len(replications)) {
set.seed(replication_seeds[replication])
simulated <- sweep(matrix(rnorm(nrow(Y) * 9), nrow(Y), 9) %*%
chol(full_moments$covariance), 2, full_moments$mean, "+")
colnames(simulated) <- colnames(Y)
data_rep <- sem_data(simulated)
fitted_rep <- tryCatch(sem_fit(full, data_rep, start = full_sem_start(data_rep)),
error = function(e) e)
estimates <- standard_errors <- setNames(rep(NA_real_, 3), parameter_names)
usable <- FALSE
reason <- if (inherits(fitted_rep, "error")) conditionMessage(fitted_rep) else
fitted_rep$optimizer$reason
if (!inherits(fitted_rep, "error")) {
usable <- isTRUE(fitted_rep$optimizer$converged) && isTRUE(fitted_rep$information$valid) &&
fitted_rep$admissibility$smallest_disturbance_eigenvalue >= -1e-8 &&
all(is.finite(fitted_rep$gradient)) &&
max(abs(fitted_rep$gradient)) / nrow(Y) < 2e-5
estimates <- fitted_rep$theta[parameter_names]
standard_errors <- fitted_rep$information$se[match(parameter_names, full$parameters)]
}
recovery[[replication]] <- data.frame(replication = replication,
seed = replication_seeds[replication], parameter = parameter_names,
estimate = unname(estimates), SE = unname(standard_errors), usable = usable, reason = reason)
if (replication %% 10L == 0L) message("Completed ", replication, " / ", replications, " replications")
}
Each row of the normal random matrix is multiplied by the upper Cholesky factor of the known response covariance and then given the population mean. Separate saved seeds make each replication reproducible. The fit is marked usable only if it passes the convergence, information, disturbance and gradient checks. Each replication contributes three records, one per structural coefficient, including its estimate, SE, seed, usability flag and stopping reason. An error leaves missing estimates and a recorded message; the diagnostic record is retained even when that replication is excluded from the summary.
The next calculation combines those records and summarizes usable fits separately for each coefficient. The coverage indicator tests whether the absolute estimation error is no larger than the normal critical value times that fit’s SE. Its average is the empirical coverage, and the binomial standard-error formula quantifies Monte Carlo uncertainty in that fraction.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
recovery <- do.call(rbind, recovery)
recovery_summary <- do.call(rbind, lapply(parameter_names, function(parameter) {
rows <- recovery[recovery$parameter == parameter & recovery$usable, ]
target <- truth[parameter]
count <- nrow(rows)
coverage <- if (count) mean(abs(rows$estimate - target) <= qnorm(.975) * rows$SE) else NA_real_
data.frame(parameter = parameter, requested = replications, usable = count,
bias = if (count) mean(rows$estimate) - target else NA_real_,
empirical_SD = if (count > 1) sd(rows$estimate) else NA_real_,
mean_SE = if (count) mean(rows$SE) else NA_real_, coverage = coverage,
coverage_MCSE = if (count) sqrt(coverage * (1 - coverage) / count) else NA_real_)
}))
print(recovery_summary, row.names = FALSE)
write.csv(recovery, file.path("data/derived/ch07", "recovery-replications.csv"), row.names = FALSE)
write.csv(recovery_summary, file.path("data/derived/ch07", "recovery-summary.csv"), row.names = FALSE)
1
2
3
4
parameter requested usable bias empirical_SD mean_SE coverage coverage_MCSE
a 200 200 -0.0080322688 0.05666106 0.05691734 0.970 0.01206234
b 200 200 0.0014231099 0.07126113 0.06512206 0.935 0.01743201
cprime 200 200 -0.0009351004 0.07073731 0.06369792 0.905 0.02073343
All 200 requested replications satisfy the convergence, gradient, admissibility and information checks, so none is excluded from this summary. The saved replication table records whether each fit passed these checks and the optimizer’s stopping reason. For each structural coefficient, bias is the mean estimate minus the generating value, empirical standard deviation (SD) describes variation of the estimates, and mean SE averages their information-based standard errors.
The observed biases are $-0.0080$ for $a$, $0.0014$ for $b$ and $-0.0009$ for $c^{\prime}$. For $a$, empirical SD $0.05666$ is close to mean SE $0.05692$, and 194 of 200 nominal 95% intervals contain the generating value. For $b$, empirical SD $0.07126$ exceeds mean SE $0.06512$, with 187 intervals covering. The difference is also present for $c^{\prime}$: empirical SD is $0.07074$, mean SE is $0.06370$, and 181 intervals cover.
Coverage is the fraction of usable normal intervals containing the generating value. Its estimated Monte Carlo standard error is $\sqrt{\hat p(1-\hat p)/R_{\rm usable}}$, giving about $0.0121$, $0.0174$ and $0.0207$ for the three rows. The estimated coverage of $c^{\prime}$ is 90.5%, below the nominal 95% despite its small bias. The lower mean SE relative to empirical SD is consistent with intervals that are too narrow on average in this experiment, although coverage also depends on the shape of the sampling distribution and its relation to estimated standard errors.
These numerical checks therefore do not establish uniformly accurate normal intervals. Agreement with an existing package verifies the implementation of the same approximation, while the replication study examines its sampling performance. With 200 replications the coverage estimates retain Monte Carlo uncertainty. The observed shortfall should be reported, rather than interpreted as nominal coverage or removed by changing the simulation. Its magnitude applies to these parameter values, sample size, measurement quality and error assumptions; the experiment does not determine coverage for every full SEM or for the empirical data.