| Title: | Latent Variable Analysis |
| Version: | 0.7-4 |
| Description: | Fit a variety of latent variable models, including confirmatory factor analysis, structural equation modeling and latent growth curve models. |
| Depends: | R(≥ 3.4) |
| Imports: | methods, parallel, stats4, stats, utils, graphics, grDevices, MASS, mnormt, pbivnorm, numDeriv, quadprog |
| BugReports: | https://github.com/yrosseel/lavaan/issues |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| LazyData: | yes |
| LazyDataCompression: | xz |
| ByteCompile: | true |
| URL: | https://lavaan.ugent.be |
| NeedsCompilation: | no |
| Packaged: | 2026-12-05 15:59:21 UTC; yves |
| Author: | Yves Rosseel |
| Maintainer: | Yves Rosseel <Yves.Rosseel@UGent.be> |
| Repository: | CRAN |
| Date/Publication: | 2026-12-05 19:10:02 UTC |
Demo dataset for illustrating a linear growth model
Description
A toy dataset containing measures on 4 time points (t1,t2, t3 and t4), two predictors (x1 and x2) influencing the random intercept and slope, and a time-varying covariate (c1, c2, c3 and c4).
Usage
data(Demo.growth)
Format
A data frame of 400 observations of 10 variables.
t1Measured value at time point 1
t2Measured value at time point 2
t3Measured value at time point 3
t4Measured value at time point 4
x1Predictor 1 influencing intercept and slope
x2Predictor 2 influencing intercept and slope
c1Time-varying covariate time point 1
c2Time-varying covariate time point 2
c3Time-varying covariate time point 3
c4Time-varying covariate time point 4
See Also
Examples
head(Demo.growth)
Demo dataset for illustrating a multilevel CFA
Description
A toy dataset containing measures on 6 items (y1-y6), 3 within-level covariates (x1-x3) and 2 between-level covariates (w1-w2). The data is clustered (200 clusters of size 5, 10, 15 and 20), and the cluster variable is “cluster”.
Usage
data(Demo.twolevel)
Format
A data frame of 2500 observations of 12 variables.
y1item 1
y2item 2
y3item 3
y4item 4
y5item 5
y6item 6
x1within-level covariate 1
x2within-level covariate 2
x3within-level covariate 3
w1between-level covariate 1
w2between-level covariate 2
clustercluster variable
Examples
head(Demo.twolevel)
model <- '
level: 1
fw =~ y1 + y2 + y3
fw ~ x1 + x2 + x3
level: 2
fb =~ y1 + y2 + y3
fb ~ w1 + w2
'
fit <- sem(model, data = Demo.twolevel, cluster = "cluster")
summary(fit)
Holzinger and Swineford Dataset (9 Variables)
Description
The classic Holzinger and Swineford (1939) dataset consists of mental
ability test scores of seventh- and eighth-grade children from two
different schools (Pasteur and Grant-White). In the original dataset
(available in the MBESS package), there are scores for 26 tests.
However, a smaller subset with 9 variables is more widely used in the
literature (for example in Joreskog's 1969 paper, which also uses the 145
subjects from the Grant-White school only).
Usage
data(HolzingerSwineford1939)
Format
A data frame with 301 observations of 15 variables.
idIdentifier
sexGender
ageyrAge, year part
agemoAge, month part
schoolSchool (Pasteur or Grant-White)
gradeGrade
x1Visual perception
x2Cubes
x3Lozenges
x4Paragraph comprehension
x5Sentence completion
x6Word meaning
x7Speeded addition
x8Speeded counting of dots
x9Speeded discrimination straight and curved capitals
Source
This dataset was originally retrieved from http://web.missouri.edu/~kolenikovs/stata/hs-cfa.dta (link no longer active) and converted to an R dataset.
References
Holzinger, K., and Swineford, F. (1939). A study in factor analysis: The stability of a bifactor solution. Supplementary Educational Monograph, no. 48. Chicago: University of Chicago Press.
Joreskog, K. G. (1969). A general approach to confirmatory maximum likelihood factor analysis. Psychometrika, 34, 183-202.
See Also
Examples
head(HolzingerSwineford1939)
Industrialization And Political Democracy Dataset
Description
The ‘famous’ Industrialization and Political Democracy dataset. This dataset is used throughout Bollen's 1989 book (see pages 12, 17, 36 in chapter 2, pages 228 and following in chapter 7, pages 321 and following in chapter 8). The dataset contains various measures of political democracy and industrialization in developing countries.
Usage
data(PoliticalDemocracy)
Format
A data frame of 75 observations of 11 variables.
y1Expert ratings of the freedom of the press in 1960
y2The freedom of political opposition in 1960
y3The fairness of elections in 1960
y4The effectiveness of the elected legislature in 1960
y5Expert ratings of the freedom of the press in 1965
y6The freedom of political opposition in 1965
y7The fairness of elections in 1965
y8The effectiveness of the elected legislature in 1965
x1The gross national product (GNP) per capita in 1960
x2The inanimate energy consumption per capita in 1960
x3The percentage of the labor force in industry in 1960
Source
The dataset was originally retrieved from http://web.missouri.edu/~kolenikovs/Stat9370/democindus.txt (link no longer valid; see discussion on SEMNET 18 Jun 2009). The dataset is part of a larger (public) dataset (ICPSR 2532), see
https://www.icpsr.umich.edu/web/ICPSR/studies/2532.
References
Bollen, K. A. (1989). Structural Equations with Latent Variables. Wiley Series in Probability and Mathematical Statistics. New York: Wiley.
Bollen, K. A. (1979). Political democracy and the timing of development. American Sociological Review, 44, 572-587.
Bollen, K. A. (1980). Issues in the comparative measurement of political democracy. American Sociological Review, 45, 370-390.
Examples
head(PoliticalDemocracy)
Alignment of a multiple-group confirmatory model
Description
The alignment option of lavOptions aligns a
multiple-group confirmatory factor model: the factor variances and means of
the configural model (with std.lv = TRUE: factor variances one and
factor means zero in every group) are chosen to minimize the amount of
measurement non-invariance of the loadings and the intercepts, following
the alignment method of Asparouhov and Muthen (2014). The aligned model has
the same fit as the configural model; it provides comparable group-specific
factor variances and means without assuming measurement invariance, and the
aligned loadings and intercepts can be inspected for (non-)invariance with
lavTestAlignment.
Usage
fit <- cfa(model, data = data, group = "g", std.lv = TRUE,
meanstructure = TRUE,
alignment = list("fixed",
method = "loading.alignment",
epsilon = 0.01,
group_weights = "sqrt.nobs",
identification = "reference",
std_ov = FALSE, rstarts = 30L,
reference_group = 1L))
The settings of the alignment are given in the alignment list
after the type of alignment (as the settings of a rotation follow the
rotation criterion in the rotation list); a list without the type
requests a fixed alignment. alignment = "fixed" alone uses the
default settings.
Options
alignment"none"(the default),"fixed"or"free", or a list with the type of alignment as its first element followed by the settings listed below. With"fixed"the factor means of the first group are fixed to zero; with"free"the means of all groups are aligned, which requires more than two groups and some loading non-invariance to be identified. The model must be a multiple-group configural model: latent variables with indicators,std.lv = TRUE, a mean structure, free loadings and intercepts in every group, no equality constraints. The model may also contain efa blocks (seeesem): they are rotated first, with the agreement rotation ifrotation = list("geomin", mg_agreement = TRUE), and the confirmatory factors are then aligned on the rotated model; the two transformations act on different factors and compose.- settings
The elements of the
alignmentlist after the type of alignment (snake_case names):method("loading.alignment", the default: the component loss(d^2 + \epsilon)^{1/4}summed over all pairs of groups and all loadings and intercepts, withdthe difference between the two parameters;"relative.alignment": the same loss on relative differences, a loading entering as\log(\lambda^2 + \epsilon)/2and an intercept difference divided by the scale of the indicator, seemg_agreement_methodinesem; this is the loss that reproduces the alignment of Mplus; or"procrustes": squared differences),epsilon(0.01),group_weights("sqrt.nobs", the default: a pair of groups is weighted by the square root of the product of their sample sizes;"nobs"or"equal"),identification("reference", the default: the solution of the product identification re-expressed with variance one in the first group;"product": the product of the factor variances is one;"mean": their average is one),std_ov(FALSE; ifTRUE, the loss is evaluated on the loadings and intercepts of the indicators standardized over the entire population, as the alignment method does),rstarts(30, the number of random starts of the loss minimization in addition to the start at equal column sums of squares) andreference_group(1, the group with variance one under the"reference"identification and mean zero underalignment = "fixed": a group number, a group label, or"auto", which tries every group as the reference of a fixed alignment and keeps the one with the smallest loss, i.e. the most invariant aligned model; withalignment = "free"the loss does not depend on the reference group and"auto"keeps the first group).
Details
The aligned loadings are the configural loadings divided by the square
roots of the aligned factor variances, the aligned intercepts are the
configural intercepts minus the aligned loadings times the aligned factor
means; all other parameters are transformed so that the model-implied
moments are unchanged (the factor covariances, the regressions among the
factors, the factor intercepts). The aligned factor variances and means
(except those fixed by the identification) are parameters of the aligned
model, with standard errors obtained by the delta method from the
configural model, or by the bootstrap (se = "bootstrap": every
bootstrap sample is refit and aligned with the same settings, and the
variability of the aligned parameters is used).
lavInspect with "rotation" returns the alignment
information per group (the aligned variances and means, the loss value,
convergence, the reference group, and the loss value of every random
start in starts), and "rotation_matrix" the diagonal
rescaling.
Two diagnostics are reported as warnings. The loss function has several
local optima when the best solution was reached by a single random
start; increase rstarts and compare the solutions. A free
alignment of the means (alignment = "free") may be poorly
identified: the overall level of the means of a factor is identified by
the loss only, and the warning is given when the standard error of the
average of the group means exceeds the largest standard error of a
difference between two group means (which is identified by the data).
This happens with few groups or little non-invariance, as Asparouhov and
Muthen (2014) describe; use the fixed alignment then.
For ordered indicators (ordered), the thresholds take the place of
the intercepts: every threshold of an indicator is a component of the
alignment loss, together with the loading of the indicator, and the
aligned thresholds are the configural thresholds plus the aligned loadings
times the aligned factor means (the intercepts of ordered indicators stay
fixed to zero); the model-implied thresholds are unchanged. Continuous and
ordered indicators can be mixed. Since the loss is not invariant to the
scale of the indicators, the solution depends on the
parameterization ("delta" or "theta") of the
configural model.
The model may contain exogenous covariates (f ~ x), with
conditional.x = TRUE or FALSE: the regressions of the
factors on the covariates transform with the factor scales, and the
aligned factor means are the intercepts of the factors given the
covariates (as in Mplus; center the covariates to keep them
interpretable as means). std_ov = TRUE is not available with
conditional.x = TRUE. Alignment is not available for multilevel
models, or when an indicator of an aligned factor is itself a predictor
or an outcome in a regression. In a model with efa blocks, the
efa factors are not aligned by this option but by the agreement rotation
(mg_agreement_scales, mg_agreement_intercepts); the
rotation information of lavInspect then holds both the
efa sets and the alignment element.
References
Asparouhov, T., & Muthen, B. (2014). Multiple-group factor analysis alignment. Structural Equation Modeling, 21(4), 495–508.
Asparouhov, T., & Muthen, B. (2023). Multiple group alignment for exploratory and structural equation models. Structural Equation Modeling, 30(2), 169–191.
See Also
lavTestAlignment for the invariance analysis of the aligned
parameters (efa and confirmatory); esem for the alignment
of efa blocks (rotation = list("geomin", mg_agreement = TRUE, ...)).
Examples
HS <- HolzingerSwineford1939
model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(model, data = HS, group = "school", std.lv = TRUE,
meanstructure = TRUE, alignment = "fixed")
lavInspect(fit, "rotation")
lavTestAlignment(fit)
Fit Confirmatory Factor Analysis Models
Description
Fit a Confirmatory Factor Analysis (CFA) model.
Usage
cfa(model = NULL, data = NULL, ordered = NULL, aux = NULL, sampling_weights = NULL,
sample_cov = NULL, sample_mean = NULL, sample_th = NULL,
sample_nobs = NULL, group = NULL, cluster = NULL, panel = NULL,
constraints = "", wls_v = NULL, nacov = NULL, ov_order = "model",
sampling_weights_cluster = NULL, ...)
Arguments
model |
A description of the user-specified model. Typically, the model
is described using the lavaan model syntax. See
|
data |
An optional data frame containing the observed variables used in the model. If some variables are declared as ordered factors, lavaan will treat them as ordinal variables. |
ordered |
Character vector. Only used if the data is in a data.frame. Treat these variables as ordered (ordinal) variables, if they are endogenous in the model. Importantly, all other variables will be treated as numeric (unless they are declared as ordered in the data.frame.) Since 0.6-4, ordered can also be logical. If TRUE, all observed endogenous variables are treated as ordered (ordinal). If FALSE, all observed endogenous variables are considered to be numeric (again, unless they are declared as ordered in the data.frame.) |
aux |
Character vector. Names of auxiliary observed variables, used to
make the missing-at-random (MAR) assumption more plausible under missing
data (continuous data only). With |
sampling_weights |
A variable name in the data frame containing
sampling weight information. Depending on the
|
sample_cov |
Numeric matrix. A sample variance-covariance matrix. The rownames and/or colnames must contain the observed variable names. For a multiple group analysis, a list with a variance-covariance matrix for each group. |
sample_mean |
A sample mean vector. For a multiple group analysis, a list with a mean vector for each group. |
sample_th |
Vector of sample-based thresholds. For a multiple group analysis, a list with a vector of thresholds for each group. |
sample_nobs |
Number of observations if the full data frame is missing and only sample moments are given. For a multiple group analysis, a list or a vector with the number of observations for each group. |
group |
Character. A variable name in the data frame defining the groups in a multiple group analysis. |
cluster |
Character. A (single) variable name in the data frame defining the clusters in a two-level dataset. |
panel |
Character. If the data are long panel data (one row per
person and occasion), the names of the id and the time variable, as in
|
constraints |
Additional (in)equality constraints not yet included in the
model syntax. See |
wls_v |
A user provided weight matrix to be used by estimator |
nacov |
A user provided matrix containing the elements of (N times)
the asymptotic variance-covariance matrix of the sample statistics.
For a multiple group analysis, a list with an asymptotic
variance-covariance matrix for each group. See the |
ov_order |
Character. If |
sampling_weights_cluster |
A variable name in the data frame containing
the sampling weights of the clusters (level-2 units). Only used for
two-level models (see the |
... |
Many more options can be specified, using 'name = value'.
See |
Details
The cfa function is a wrapper for the more general
lavaan function, using the following default arguments:
int_ov_free = TRUE, int_lv_free = FALSE,
auto_fix_first = TRUE (unless std_lv = TRUE),
auto_fix_single = TRUE, auto_var = TRUE,
auto_cov_lv_x = TRUE, auto_efa = TRUE,
auto_th = TRUE, auto_delta = TRUE,
auto_cov_y = TRUE, and auto_cov_rv = TRUE (unless
mimic = "Mplus").
Value
An object of class lavaan, for which several methods
are available, including a summary method.
References
Yves Rosseel (2012). lavaan: An R Package for Structural Equation Modeling. Journal of Statistical Software, 48(2), 1-36. doi:10.18637/jss.v048.i02
See Also
lavaan, estimator_iv, estimator_js
Examples
## The famous Holzinger and Swineford (1939) example
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data = HolzingerSwineford1939)
summary(fit, fit_measures = TRUE)
Exploratory Factor Analysis
Description
Fit one or more Exploratory Factor Analysis (EFA) model(s).
Usage
efa(data = NULL, nfactors = 1L, sample_cov = NULL, sample_nobs = NULL,
rotation = "geomin", rotation_args = list(), ov_names = NULL,
bounds = "pos.var", ..., output = "efa")
Arguments
data |
A data frame containing the observed variables we need for the
EFA. If only a subset of the observed variables is needed, use the
|
nfactors |
Integer, integer vector, or a list. The desired number of
factors to extract. Can be a single number, or a vector of numbers
(e.g., |
sample_cov |
Numeric matrix. A sample variance-covariance matrix.
The rownames and/or colnames must contain the observed variable names.
Unlike sem and CFA, the matrix may be a correlation matrix: if all
variances are one (and no |
sample_nobs |
Number of observations if the full data frame is missing and only the sample variance-covariance matrix is given. |
rotation |
Character or a list with first element a character variable.
The character variable is the rotation method to be used. Possible options
are varimax, quartimax, orthomax, oblimin, quartimin, geomin, promax,
entropy, mccammon, infomax, tandem1, tandem2, oblimax, bentler, simplimax,
target.strict, target (alias for pst), pst (=partially specified target),
cf, crawford-ferguson,
cf-quartimax, cf-varimax, cf-equamax,
cf-parsimax, cf-facparsim, biquartimin, bigeomin. The latter two are
for bifactor rotation only. The rotation algorithms (except promax
and target) are similar to those from the GPArotation package, but have
been reimplemented for better control. The promax method is taken from the
stats package. The target.strict method is equal to the target method in
the GPArotation package. The target method is in fact the pst method where
all non-zero elements (in the target matrix) are ignored.
Options for the rotation algorithm can be provided in the list after the method.
The default options (and their alternatives) are For the target rotation methods ( |
rotation_args |
List. Options related to the rotation algorithm. DEPRECATED.
The options should now be given in the |
ov_names |
Character vector. The variables names that are needed for
the EFA. Should be a subset of the variables names in the data.frame.
By default (if NULL), all the variables in the data are used. For long
panel data (with the |
bounds |
Per default, |
... |
Additional options to be passed to lavaan, using 'name = value'.
See |
output |
Character. If |
Details
The efa function is essentially a wrapper around the
lavaan function. It generates the model syntax (for a given number
of factors) and then calls lavaan() treating the factors (in each
block) as a set that should be rotated. Each block is rotated
independently. Categorical data is handled as usual by first computing
an appropriate (e.g., tetrachoric or polychoric) correlation matrix,
which is then used as input for the EFA.
Multiple groups (via the group= argument) and twolevel data
(via the cluster= argument) are supported, and these may be
combined. By default, the same number of factors is extracted in every
block, but a different number of factors per block can be requested by
supplying nfactors as a list (see the nfactors argument).
If the factor loadings are constrained to be equal across groups
(group_equal = "loadings"), a single rotation (based on the
first group) is used for all groups. The factor variances and covariances
are then fixed (to unity and, for an orthogonal rotation, to zero) in
the first group only, and they are freely estimated in the other
groups, even if orthogonal = TRUE. To force the same factor
covariance matrix in all groups, add both "lv.variances" and
"lv.covariances" to group_equal.
The promax rotation method (taken from the stats package) is only
provided for convenience. Because promax is a two-step algorithm (first
varimax, then oblique rotation to get simple structure), it does not
use the gpa or pairwise rotation algorithms, and as a result, no
standard errors are provided.
Value
If output = "lavaan", an object of class
lavaan. If output = "efa",
a list of class efaList for which a print(),
summary() and fitMeasures() method are available. Because
we added the (standardized) loadings as an extra element, the loadings
function (which is not a generic function) from the stats package will
also work on efaList objects.
See Also
lav_efalist_summary for a summary method if the output is
of class efaList; esem for exploratory structural
equation modeling, where one or more sets of exploratory factors (defined
with the efa() modifier in the model syntax) are combined with a
structural part, confirmatory factors, or other sets.
Examples
## The famous Holzinger and Swineford (1939) example
fit <- efa(data = HolzingerSwineford1939,
ov.names = paste("x", 1:9, sep = ""),
nfactors = 1:3,
rotation = list("geomin", geomin_epsilon = 0.01, rstarts = 1))
summary(fit, nd = 3L, cutoff = 0.2, dot.cutoff = 0.05)
fitMeasures(fit, fit_measures = "all")
# target rotation
target <- matrix(0, 9, 3)
target[1:3, 1] <- 1
target[4:6, 2] <- 1
target[7:9, 3] <- 1
fit2 <- efa(data = HolzingerSwineford1939,
ov.names = paste("x", 1:9, sep = ""),
nfactors = 3,
rotation = list("target", target = target))
summary(fit2)
## Not run:
# twolevel EFA with a different number of factors per level:
# one factor at the within level, two factors at the between level
fit3 <- efa(data = Demo.twolevel, ov.names = paste0("y", 1:6),
cluster = "cluster", nfactors = list(c(1, 2)))
summary(fit3)
## End(Not run)
Exploratory Structural Equation Modeling
Description
Exploratory Structural Equation Modeling (ESEM) combines the flexibility of
exploratory factor analysis (EFA) with the modeling options of structural
equation modeling (SEM). In lavaan, this is done by marking one or more
sets of latent variables in the model syntax with the efa()
modifier. The factors within a set form a block of exploratory factors: all
their factor loadings are (in principle) freely estimated, and the block is
rotated after the model has been fitted. The rest of the model (confirmatory
factors, regressions, covariates, residual covariances, multiple groups,
multiple levels, ...) is specified as usual.
This page explains how such sets of factors are defined, what lavaan does to identify them, gives a brief overview of the available rotation methods and options, and shows how to use a different target matrix per set in a target rotation.
Details
Defining a set of exploratory factors
A set is defined by premultiplying the latent variable names (on the left-hand
side of the =~ operator) by the efa("label") modifier, where
"label" is an arbitrary name for the set. All latent variables that
carry the same label belong to the same set:
efa("block1")*f1 +
efa("block1")*f2 +
efa("block1")*f3 =~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
Each factor in the set should load on the same indicators (here, all of
x1 to x9). Using different labels defines different sets, for
example one set per measurement occasion or per questionnaire:
efa("t1")*f1 + efa("t1")*f2 =~ y1 + y2 + y3 + y4 + y5 + y6
efa("t2")*f3 + efa("t2")*f4 =~ y7 + y8 + y9 + y10 + y11 + y12
Each set is rotated independently of the other sets; this is sometimes
called set-ESEM. A set with a single factor is not rotated. Sets can be freely
combined with confirmatory (CFA) factors, with regressions among the factors
(exploratory or not), with observed covariates, and with residual covariances.
For a single set of factors without any further structure, the
efa function provides a convenient wrapper.
Identification of the unrotated solution
Within a set, the factors are not identified without further constraints.
By default (auto_efa = TRUE; see lavOptions), lavaan
imposes the constraints that are needed to identify the unrotated
solution: the variances of the factors in the set are fixed to 1, their
covariances are fixed to zero, and the factor loadings follow an echelon
pattern (the loading of the second factor on the first indicator is fixed to
zero, the loadings of the third factor on the first two indicators are fixed
to zero, and so on). The unrotated solution can be inspected by setting
rotation = "none".
After the model has been fitted, the loadings of each set are rotated, and the remaining parameters that depend on the factors (factor covariances, regression coefficients, intercepts) are transformed accordingly, so that the reported solution is the rotated one. For oblique rotations, the factor covariances within a set are reported as free parameters. Standard errors for the rotated solution are obtained by one of the methods described below.
The structural part of the model can be specified in terms of the (rotated)
factors in the usual way, for example
f3 + f4 ~ f1 + f2 or f1 + f2 + f3 ~ age + sex. Because the
rotation is chosen by the rotation criterion, and not by the structural part
of the model, the rotation does not depend on the regressions.
Rotation methods
The rotation method is selected by the rotation argument (the default
is "geomin"). It applies to all sets in the model; for a model
without efa() sets there is nothing to rotate, and an explicit
rotation (or rotation_args) argument is ignored with a
warning. By default, the rotation is oblique; an orthogonal rotation is requested by setting the
orthogonal element of rotation_args to TRUE. The
following criteria are available; most of them are available in both an
orthogonal and an oblique version:
-
"varimax","quartimax","orthomax"(withorthomax_gamma),"entropy","mccammon","infomax","tandem1","tandem2": classic criteria that are typically used for orthogonal rotation. -
"oblimin"(withoblimin_gamma),"quartimin","geomin"(withgeomin_epsilon),"oblimax","simplimax"(making thep(m-1)smallest loadings as close to zero as possible, as in GPArotation 2026.8 and later),"bentler": criteria that are typically used for oblique rotation. -
"cf"(Crawford-Ferguson, withcf_gamma), and its special cases"cf-quartimax","cf-varimax","cf-equamax","cf-parsimax"and"cf-facparsim". -
"target.strict","target"and"pst": target rotation, where the loadings are rotated towards a user-specified target matrix (see below). -
"biquartimin"and"bigeomin": bifactor rotation, where the first factor of the set is a general factor. -
"promax": the two-step promax method from the stats package (varimax followed by an oblique rotation). No standard errors are available for this method. -
"none": no rotation; the unrotated (echelon) solution is reported.
The rotation is found by minimizing the criterion with the gradient
projection algorithm (algorithm = "gpa", the default) or with a
pairwise algorithm (algorithm = "pairwise"; one pair of factors at a
time, each plane minimized exactly using the gradient of the criterion, or
by a derivative-free search for simplimax), starting from a number of
random starts (rstarts, default 30) to avoid local minima. Both
algorithms stop when the projected gradient of the criterion falls below
gpa_tol. The pairwise algorithm is also used for the multiple-group
agreement rotation (mg_agreement = TRUE).
Rotation options
Options for the rotation are given as a list in the rotation_args
argument (they can also be given as additional elements of a list in the
rotation argument, see efa). The most important ones
are:
orthogonalLogical. If
TRUE, the factors within a set are kept uncorrelated. Default:FALSE(oblique rotation).row_weightsStandardization of the rows of the loading matrix before rotation:
"default","kaiser","cureton.mulaik"or"none". The default is"kaiser"for varimax and promax, and"none"for all other criteria.std_ovLogical. If
TRUE(the default), the rotation is carried out on the loadings in the standardized (correlation) metric of the indicators; the result is transformed back to the original metric. In the agreement rotation of a multiple-group model (mg_agreement = TRUE) this applies to the per-group rotation that provides the starting point; the agreement objective itself is evaluated in the original metric (seemg_agreement_std_ov).rstartsInteger. The number of random starts for the rotation algorithm. Default:
30.algorithm"gpa"(gradient projection, the default) or"pairwise".pairwise_accelerateLogical. If
TRUE(the default), the pairwise algorithm extrapolates the solution across sweeps (an Aitken-type step along the last sweep displacement, accepted only if it lowers the criterion), which reduces the number of sweeps on slowly converging problems.gpa_algorithmStep size strategy of the gradient projection algorithm:
"bb"(Barzilai-Borwein with a non-monotone line search, the default),"cayley"(orthogonal rotation only) or"legacy". Seeefaforgpa_fwindow.geomin_epsilon,orthomax_gamma,oblimin_gamma,cf_gamma,promax_kappa,simplimax_kTuning constants of the corresponding criteria. Defaults:
0.001,1,0,0,4and0, wheresimplimax_k = 0means that thep(m-1)smallest loadings are driven to zero.target,target_maskThe target matrix (and optional mask) for the target rotation methods; see below.
reflectLogical. If
TRUE(the default), the sign of each rotated factor is chosen such that the sum of its loadings is positive.order_lv_byHow the rotated factors within a set are ordered:
"index"(the default; the factor whose largest loading is on the earliest indicator comes first),"sumofsquares"or"none". For target rotation, the order is always"none"(the order of the columns of the target matrix). For bifactor rotation, the general factor always stays in the first position, and the ordering rule is applied to the specific factors only.mg_agreementLogical or character. For multiple-group models only. If
TRUE, the rotated solutions of the groups are made as similar as possible (see alsomg_agreement_weight,mg_agreement_method,mg_agreement_epsilon,mg_agreement_group_weights,mg_agreement_scales,mg_agreement_rotate,mg_agreement_intercepts,mg_agreement_identification,mg_agreement_std_ovandmg_agreement_algorithm). Two presets fill in these options (and the rotation criterion and the mean structure) for the user, who may still override any of them explicitly:"mgfr"is the multigroup factor rotation of De Roover and Vermunt (2019), a joint oblimin rotation of all groups with the generalized procrustes agreement term, free factor scales (mean variance one) and equal group weights (mg_agreement_weight = 1/3, which is the unweighted combination of the procrustes and oblimin criteria recommended in that paper, as lavaan's oblimin is half theirs);"alignment"is the alignment of Mplus for an ESEM (Asparouhov and Muthen, 2014): a per-group geomin rotation (geomin_epsilon = 0.01, standardized indicators) followed by the alignment of the factor variances and means (fixed alignment: variance one and mean zero in the first group,mg_agreement_intercepts = "fixed", withmeanstructure = TRUE) under the relative-difference loss (mg_agreement_method = "relative.alignment") with the"sqrt.nobs"group weights. The preset used is recorded inmg_agreement_preset. A preset may be given inrotation.argsor inside therotationlist (for examplerotation = list("oblimin", mg_agreement = "mgfr")); the other values in that list win over the preset values either way.mg_agreement_preset"none"(the default),"mgfr"or"alignment": the preset of the agreement rotation (seemg_agreement); set by giving the preset as the value ofmg_agreement.mg_agreement_method"procrustes"(the default),"loading.alignment"or"relative.alignment": the agreement term. Procrustes: the sum of squared differences between the loadings of every pair of groups. Loading alignment: the component loss of the alignment method (Asparouhov and Muthen, 2014), the sum over all pairs and loadings of(d^2 + \epsilon)^{1/4}withdthe difference between two loadings and\epsilon=mg_agreement_epsilon(default 0.01). Small differences are penalized more than proportionally and large ones less, so that the solution has many (nearly) invariant loadings and a few large differences. Relative alignment: the same component loss, but on relative differences: a loading enters as\log(\lambda^2 + \epsilon)/2, so thatdis the log ratio of two loadings (damped to zero for loadings near zero), and a difference between two intercepts (seemg_agreement_intercepts) is divided by the scale of the indicator (the average over the two groups of\sqrt{\sum_j \lambda_{ij}^2 + \epsilon}). This loss is (nearly) invariant to the scale of the indicators, and reproduces the factor variances and means of the alignment of Mplus, which the raw-difference loss does not.mg_agreement_group_weights"equal"(the default),"nobs"or"sqrt.nobs": whether the groups are weighted by their sample sizes in the agreement criterion (the per-group criteria by the group weight, and each pair of groups in the agreement term by the product of the two weights). With"nobs"the group weights are proportional to the sample sizes; with"sqrt.nobs"to their square roots, so that a pair of groups is weighted by the square root of the product of the two sample sizes, as in the alignment method.mg_agreement_rotateLogical (default
TRUE). IfFALSE, the per-group rotated solutions (aligned to the first group) are kept as they are, and only the split of the scale of each factor over the groups is optimized for agreement (which requiresmg_agreement_scales = "free"; with"equal"nothing moves). With a (partially specified) target rotation towards a confirmatory pattern,mg_agreement_method = "loading.alignment",mg_agreement_weight = 1andmg_agreement_group_weights = "sqrt.nobs", this is the alignment of the factor loadings and variances of Asparouhov and Muthen (2014); addmg_agreement_intercepts = "fixed"for the alignment of the intercepts.mg_agreement_identification"mean"(the default),"product"or"reference": how the overall scale of each factor is identified in the agreement rotation. The factor variances average to one across groups, have a product of one, or the variance in the first group is one. With free scales,"reference"is the solution of the product identification re-expressed with variance one in the first group, as the alignment method reports it (optimizing the alignment loss directly in that metric is degenerate). With equal scales, the common column sum of squares is the group average, the geometric mean, or the first group's.mg_agreement_reference_groupThe reference group of the agreement rotation (default 1): a group number or a group label. Its factor variances are one under
mg_agreement_identification = "reference", its factor means are zero undermg_agreement_intercepts = "fixed", and the factors of the other groups are matched to its factors. In the scales-only mode (mg_agreement_rotate = FALSE) a warning is given when the best solution was reached by a single random start (local optima), and withmg_agreement_intercepts = "free"when the alignment of the means is poorly identified (seealignment).mg_agreement_std_ovLogical (default
FALSE; not available withconditional.x = TRUE). IfTRUE, the agreement objective is evaluated on the loadings of the indicators standardized over the entire population (the model-implied variances and means of the groups, pooled by sample size), as the alignment method does. The rotation matrices, scales and factor means are the same in both metrics, so only the solution changes, not its representation.mg_agreement_intercepts"none"(the default),"fixed"or"free": the alignment of the intercepts (requires a mean structure; with exogenous covariates, the aligned factor means are the intercepts of the factors given the covariates). The means of the efa factors become variables of the agreement objective ("fixed": zero in the first group;"free": free in every group, which needs more than two groups and some non-invariance to be identified), and the aligned intercepts of the indicators, the unrotated intercepts minus the loadings times the factor means, enter the agreement term along with the loadings. The rotated model is translated accordingly (the factor means and the intercepts change, the model-implied moments do not); the aligned factor means are parameters of the rotated model, with standard errors. For ordered indicators, the thresholds take the place of the intercepts: every threshold is a component of the agreement term, and the aligned thresholds are the unrotated thresholds plus the loadings times the factor means (the intercepts of ordered indicators stay fixed to zero).mg_agreement_scales"equal"(the default) or"free": how the scale of each factor is split over the groups. The agreement criterion is evaluated on loadings whose factors have, on average over the groups, unit variance. With"equal", the loadings are rescaled so that the sum of squares of every column is the same in all groups; the group-specific factor variances follow from the rotation. With"free", the split is part of the agreement objective (the multigroup factor rotation of De Roover and Vermunt, 2019): the factor variances are free, subject to a mean of one across groups. Only for criteria that are bounded below when the loadings of a factor are scaled up (oblimin withoblimin_gamma = 0, quartimin, geomin, the Crawford-Ferguson family, target, pst, simplimax, bi-quartimin and bi-geomin). Note that the oblimin criterion of lavaan is half the one used in that paper, so that their weightwcorresponds tomg_agreement_weight = w / (2 - w).mg_agreement_algorithm"gpa"(the default) or"pairwise": the algorithm for the agreement rotation of all groups together (the gradient projection algorithm on the rotation matrices of all groups jointly, or the plane-sweep algorithm). For simplimax, the plane-sweep algorithm is always used.gpa_tol,tol,max_iter,warn,verboseConvergence tolerances, the maximum number of iterations, and reporting options of the rotation algorithm.
gpa_tol(default1e-05) is the tolerance on the projected gradient of the criterion, used by both algorithms;tol(default1e-08) is the tolerance on the change of the criterion between sweeps, used only by the derivative-free plane search of the pairwise algorithm (simplimax, or a criterion without a gradient).
A complete list (with defaults) is given in the description of the
rotation argument of efa.
Target rotation and set-specific targets
A target rotation rotates the loadings of a set towards a user-specified
target matrix. The rows of the target matrix correspond to the
indicators of the set (in the order in which they appear in the model syntax),
and the columns to the factors of the set (in the order in which they appear
in the model syntax). The methods differ in how the elements of the target are
used:
-
"target.strict": all elements of the target matrix are used. -
"target"(the default alias for"pst", partially specified target): only the zero elements of the target matrix are used; the non-zero elements are ignored. In other words, the target specifies where the (near) zero loadings should be, without specifying the size of the other loadings. -
"pst"with an explicittarget_mask: the mask is a matrix of the same dimensions as the target, with a1for the elements that should be used, and a0for the elements that should be ignored. If elements of the target areNA, a mask is created automatically (theNAelements are ignored).
The target (and target_mask) option can take three forms:
A single matrix, used for every set and every group. This only works if all sets have the same number of indicators and factors.
A nameless list of matrices, one per group (the same target is then used for all sets in a given group).
A named list of matrices, where the names are the set labels used in the model syntax, so that each set gets its own target matrix (the same targets are then used in all groups). For example, if the model contains the sets
efa("t1")andefa("t2"), userotation_args = list(target = list(t1 = target_t1, t2 = target_t2)). A named list must provide a target for every set (with two or more factors) in the model; omitting a set results in an error.
Standard errors
Standard errors for the rotated solution are computed analytically. By
default (rotation_se = "bordered"), the information matrix is
augmented with the rotation constraints; alternatively,
rotation_se = "delta" applies the delta method to the (numerical)
Jacobian of the rotation. Both methods give the same results up to numerical
precision. For the multiple-group agreement rotation (mg_agreement =
TRUE), the rotation constraints of the bordered method are not those of the
joint rotation, and the delta method is always used (rotation_se is
set to "delta"). When se = "bootstrap" is requested, the rotation is applied
to every bootstrap sample, and the rotated factors are aligned (reordered and
reflected) to the original solution; see bootstrapLavaan. Robust
standard errors (for example, estimator = "MLR") are supported as
well.
References
Asparouhov, T., & Muthen, B. (2009). Exploratory structural equation modeling. Structural Equation Modeling, 16(3), 397–438.
Marsh, H. W., Morin, A. J. S., Parker, P. D., & Kaur, G. (2014). Exploratory structural equation modeling: An integration of the best features of exploratory and confirmatory factor analysis. Annual Review of Clinical Psychology, 10, 85–110.
Browne, M. W. (2001). An overview of analytic rotation in exploratory factor analysis. Multivariate Behavioral Research, 36(1), 111–150.
Asparouhov, T., & Muthen, B. (2014). Multiple-group factor analysis alignment. Structural Equation Modeling, 21(4), 495–508.
De Roover, K., & Vermunt, J. K. (2019). On the exploratory road to unraveling factor loading non-invariance: A new multigroup rotation approach. Structural Equation Modeling, 26(6), 905–923.
See Also
efa for exploratory factor analysis (a single set of factors
without a structural part), including the complete list of rotation options;
sem and lavaan for fitting the model;
lavOptions for the auto_efa, rotation,
rotation_args and rotation_se options; bootstrapLavaan
for bootstrap standard errors of a rotated solution.
Examples
## 1. a single set of three exploratory factors (this is equivalent to
## efa(data = HolzingerSwineford1939, nfactors = 3, ov_names = ...))
model1 <- '
efa("block1")*f1 +
efa("block1")*f2 +
efa("block1")*f3 =~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
'
fit1 <- sem(model1, data = HolzingerSwineford1939, rotation = "geomin")
summary(fit1, standardized = TRUE)
# the unrotated (echelon) solution
fit1u <- sem(model1, data = HolzingerSwineford1939, rotation = "none")
lavInspect(fit1u, "est")$lambda
# orthogonal varimax rotation, with a different number of random starts
fit1v <- sem(model1, data = HolzingerSwineford1939, rotation = "varimax",
rotation_args = list(orthogonal = TRUE, rstarts = 10))
lavInspect(fit1v, "est")$lambda
## 2. ESEM: the exploratory factors are regressed on observed covariates
model2 <- '
efa("block1")*f1 +
efa("block1")*f2 +
efa("block1")*f3 =~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
f1 + f2 + f3 ~ ageyr + sex
'
fit2 <- sem(model2, data = HolzingerSwineford1939, rotation = "geomin")
parameterEstimates(fit2, output = "text")
## 3. a set of two exploratory factors combined with a confirmatory factor
model3 <- '
efa("block1")*f1 +
efa("block1")*f2 =~ x1 + x2 + x3 + x4 + x5 + x6
speed =~ x7 + x8 + x9
speed ~ f1 + f2
'
fit3 <- sem(model3, data = HolzingerSwineford1939, rotation = "oblimin")
summary(fit3)
## Not run:
## (examples 4 and 5 are not run, to limit the running time)
## 4. two sets of factors (two measurement occasions), with a structural
## part, and a different target matrix per set
pop_model <- '
f1 =~ 0.8*y1 + 0.7*y2 + 0.6*y3 + 0.3*y4 + 0.0*y5 + 0.0*y6
f2 =~ 0.0*y1 + 0.0*y2 + 0.3*y3 + 0.6*y4 + 0.7*y5 + 0.8*y6
f3 =~ 0.8*y7 + 0.7*y8 + 0.6*y9 + 0.3*y10 + 0.0*y11 + 0.0*y12
f4 =~ 0.0*y7 + 0.0*y8 + 0.3*y9 + 0.6*y10 + 0.7*y11 + 0.8*y12
f1 ~~ 0.3*f2
f3 ~~ 0.3*f4
f3 ~ 0.6*f1
f4 ~ 0.6*f2
y1 ~~ 0.2*y7
y2 ~~ 0.2*y8
y3 ~~ 0.2*y9
y4 ~~ 0.2*y10
y5 ~~ 0.2*y11
y6 ~~ 0.2*y12
'
set.seed(1234)
Data <- simulateData(pop_model, sample_nobs = 500)
model4 <- '
# set "t1": two exploratory factors at time 1
efa("t1")*f1 +
efa("t1")*f2 =~ y1 + y2 + y3 + y4 + y5 + y6
# set "t2": two exploratory factors at time 2
efa("t2")*f3 +
efa("t2")*f4 =~ y7 + y8 + y9 + y10 + y11 + y12
# structural part
f3 ~ f1 + f2
f4 ~ f1 + f2
# residual covariances of the repeated indicators
y1 ~~ y7
y2 ~~ y8
y3 ~~ y9
y4 ~~ y10
y5 ~~ y11
y6 ~~ y12
'
# geomin rotation (each set is rotated independently)
fit4 <- sem(model4, data = Data, rotation = "geomin")
summary(fit4)
# target rotation with a different target per set: the rows of each
# target are the indicators of the set, the columns are its factors
target_t1 <- matrix(0, 6, 2)
target_t1[1:3, 1] <- 1
target_t1[4:6, 2] <- 1
target_t2 <- matrix(0, 6, 2)
target_t2[1:4, 1] <- 1
target_t2[5:6, 2] <- 1
fit4t <- sem(model4, data = Data, rotation = "target",
rotation_args = list(target = list(t1 = target_t1,
t2 = target_t2)))
lavInspect(fit4t, "est")$lambda
# partially specified target: NA elements are ignored (the cross-loadings
# of y3 and y4 are left unspecified in set "t1")
target_t1_pst <- target_t1
target_t1_pst[3:4, ] <- NA
fit4p <- sem(model4, data = Data, rotation = "pst",
rotation_args = list(target = list(t1 = target_t1_pst,
t2 = target_t2)))
lavInspect(fit4p, "est")$lambda
## 5. multiple groups, with equal loadings across groups
fit5 <- sem(model1, data = HolzingerSwineford1939, group = "school",
rotation = "geomin", group_equal = "loadings")
lavInspect(fit5, "est")$Pasteur$lambda
## End(Not run)
Instrumental Variable (MIIV-2SLS) Estimation
Description
Estimate a structural equation model using model-implied instrumental
variables and two-stage least squares (MIIV-2SLS), a non-iterative,
equation-by-equation alternative to maximum likelihood (Bollen, 1996).
This page documents how to invoke the estimator, the options that can be
passed via the estimator = list() argument, how to specify
instruments manually with the |~ operator, and the lavInspect()
fields that are relevant for IV estimation.
Details
Instead of minimizing a single discrepancy function for the whole model, MIIV-2SLS estimates each measurement and structural equation separately by two-stage least squares (2SLS). For each equation, the instruments are other observed variables in the model that are (under the hypothesized model) uncorrelated with the equation's composite error term: the model-implied instrumental variables (MIIVs). Because the equations are estimated separately, a misspecification in one equation does not necessarily propagate to the others, the method is non-iterative, and no starting values are required.
The estimator is selected by setting estimator = "IV" (the alias
"MIIV" is also accepted; names are case-insensitive), for example
fit <- sem(model, data = Data, estimator = "IV")
Estimation proceeds in two stages. In the first stage, the directed
effects (factor loadings and regression coefficients) are estimated
equation-by-equation by 2SLS. In the second stage, the undirected
effects (residual variances and covariances) are estimated by a weighted
least-squares step applied to the residual moments. Standard errors are
available for both stages (see the options below). The summary()
header reports them as Delta (all analytic standard errors for the
non-iterative estimators are delta-method expressions over the sample
moments), followed by the methods used for the two parts of the model
(iv_vcov_stage1, iv_vcov_stage2) and the flavor of the
moment covariance (Gamma matrix: NT, ADF or TS).
Both continuous and ordered-categorical data are supported (for ordered data,
the polychoric-based PIV estimator of Bollen & Maydeu-Olivares, 2007 is used).
The observed variables can also be a mix of numeric and ordered variables: the
sample statistics are then the thresholds, the means and variances of the
numeric variables, and the polychoric and polyserial correlations and the
covariances (the numeric variables keep their own metric), and the standard
errors are based on the asymptotic covariance matrix of all these statistics.
In the mixed setting, the intercept of a numeric marker indicator is fixed to
zero and the mean of its factor is freely estimated (as for continuous data);
the mean of a factor with an ordered marker indicator is fixed to zero. The
thresholds, the intercepts of the numeric variables and the latent means are
then solved jointly from the sample thresholds and means: if a latent mean is
not zero, the thresholds of the ordered indicators of that factor are no
longer equal to the sample thresholds.
In a multiple-group analysis of ordered data, the thresholds can be
constrained to be equal across groups (e.g.
group_equal = c("loadings", "thresholds")). The scaling factors
(~*~) and the intercepts of the ordered variables are then free in the
second and later groups (delta parameterization). A free scaling factor is
estimated first, from the thresholds only: it is the slope of the
least-squares regression of the sample thresholds of the variable in that
group on its sample thresholds in the group(s) where the scaling factor is
fixed. This needs at least two thresholds (three response categories) of the
variable that are equal across these groups; otherwise, an error is produced.
The first stage then uses the sample statistics rescaled to the metric of the
latent response variables of the model (where the loadings can be pooled
across groups), and the thresholds, intercepts and latent means are again
solved jointly. The standard errors of all the parameters take the sampling
variability of the scaling factors into account. Equality constraints among
the scaling factors and external instruments are not supported in combination
with free scaling factors.
The theta parameterization (parameterization = "theta") is also
supported. The residual variances of the latent response variables are then
fixed (to one), and their total variances are no longer one: the scaling
factor of a latent response is the square root of the ratio of its unique
variance in the correlation metric and its residual variance in the model. The
unique variances are estimated first, by a preliminary fit in the correlation
metric that ignores all equality constraints (per-equation 2SLS, followed by
ULS for the variances and covariances); if the residual variance of an
ordered variable is free (in the second and later groups, if the thresholds
are equal across groups), its scaling factor is based on the thresholds, as
above. The sample statistics are then rescaled to the metric of the latent
response variables of the model, the first stage (including the pooling
of equal parameters) and the second stage are computed in that metric, and
the thresholds, intercepts and latent means are solved jointly. Without
equality constraints, the standardized solution and the test statistic are
identical to those of the delta parameterization. The standard errors are
based on a numerical Jacobian of the complete estimator (and the covariance
matrix of the parameters has no zero blocks). External instruments are not
supported in combination with the theta parameterization.
The covariance matrix of the parameters is assembled block by block (the
directed parameters, per equation for the "lm.vcov" flavours; the
variances and covariances; the thresholds). The covariances between these
blocks (and between the equations) are based on the delta method (the
Jacobians of the blocks over the sample statistics, combined with the
covariance matrix of the sample statistics), rescaled to the standard errors
of the blocks. They are needed for the standard errors of functions that
combine parameters of different blocks or equations: the standardized
solution, defined parameters (:=), and Wald tests. (They remain zero
for external instruments with continuous data, for the raw-data engine
without a moment Jacobian, and if iv_vcov_stage1 = "none".)
Simple equality constraints (e.g. equal factor loadings) and general linear
equality constraints (e.g. a == 2*b) are honored. Multiple groups are
supported, with standard errors (for continuous, two-stage-missing and
categorical data), including the mean structure and cross-group equality
constraints for measurement invariance testing (configural, metric and scalar,
e.g. via group_equal = c("loadings", "intercepts")). For scalar
invariance the latent-mean (and intercept) estimates are obtained by a joint
GLS solve over the mean structure (see iv_mean_structure), which matches
the maximum likelihood mean estimates given the model-implied covariance
matrix. The IV estimator is restricted to single-level models.
Estimator options
Options specific to the IV estimator are passed as named elements of a list
to the estimator argument, alongside the estimator name:
fit <- sem(model, data = Data,
estimator = list(estimator = "IV",
iv_varcov_method = "2RLS",
iv_sargan_adjust = "BH"))
The option names use snake_case. For backward compatibility, dot.case names
(e.g. iv.varcov.method) are also accepted and silently converted.
iv_method:Character. The instrumental-variable method used for the first-stage (directed) coefficients. One of
"2SLS"(two-stage least squares, the default),"LIML"(limited-information maximum likelihood; Anderson & Rubin, 1949) or"FULLER"(Fuller's, 1977, modification of LIML). All three are k-class estimators computed from the same per-equation sample moments: 2SLS usesk = 1, LIML usesk = \lambda, the smallest generalized eigenvalue of the (outcome, regressors) covariance matrix relative to its conditional (given the instruments) counterpart, and Fuller usesk = \lambda - c/(N - n_z - 1)withn_zthe number of instruments (seeiv_fuller_c). For an exactly identified equation\lambda = 1, so LIML and 2SLS coincide. The estimators are asymptotically equivalent, but with many (weak) instruments 2SLS can exhibit substantial finite-sample bias, which LIML largely avoids; Fuller's modification in addition ensures finite moments. LIML and FULLER therefore allow retaining the full set of model-implied instruments (and their overidentifying restrictions) without an instrument-selection step (Maydeu-Olivares, Fisher, Bollen & Rosseel, 2026).iv_fuller_c:Numeric. The positive constant
cof the Fuller (1977) correctionk = \lambda - c/(N - n_z - 1); only used wheniv_method = "FULLER". Default is1(approximately unbiased estimates);c = 4is sometimes used to minimize the mean squared error.iv_samplestats:Logical. If
TRUE(the default), the equations are estimated from the sample moments (covariances and means) rather than from the raw data. This is required for categorical data and when only sample moments are provided as input.iv_varcov_method:Character. The second-stage method used to estimate the residual variances and covariances. One of
"ULS","GLS","2RLS","RLS"or"NONE". Default is"RLS"(reweighted least squares). For categorical data,"ULS"is used. If"NONE", the variance/covariance parameters are not estimated.iv_sargan:Logical. If
TRUE(the default), overidentification tests are computed for each overidentified equation. Two tests are reported side by side: the classical Sargan test (Sargan, 1958), which assumes normality (continuous data) and is not valid for polychoric correlations; and a robust, residual-based test that is valid more generally. The robust test is Browne's (1984) residual statistic applied to the single equation, computed with the asymptotic covariance matrix (ACOV) of the sample statistics: the distribution-free (ADF) ACOV of the sample covariances for continuous data (so it is robust to non-normality, and is then equivalent to Hansen's overidentification test), or the polychoric ACOV for categorical data. Both tests share the same degrees of freedom (number of instruments minus number of regressors). For continuous data with missing values the robust test is not available. The results can be retrieved withlavInspect(fit, "sargan")(or, equivalently,lavInspect(fit, "hansen")).iv_sargan_adjust:Character. A multiple-comparison adjustment applied to the per-equation overidentification p-values, using any method accepted by
p.adjust("holm","hochberg","hommel","bonferroni","BH","BY","fdr", or"none"). Default is"none". When a method other than"none"is requested, extrasargan.pval.adjandbrowne.pval.adjcolumns are added to the table returned bylavInspect(fit, "sargan").iv_weak:Character. How to respond to weak instruments, diagnosed per equation by the first-stage F-statistic (Staiger & Stock, 1997). One of:
"warn":(the default) report the affected equations and their first-stage F, and suggest supplying stronger instruments manually; the estimates are not changed.
"prune":greedily drop the weakest excess instruments from weak, overidentified equations (never below just-identified) and report what was dropped.
"none":skip the weak-instrument check.
iv_weak_threshold:Numeric. The first-stage F-statistic below which instruments are deemed weak. Default is
10.iv_vcov_stage1:Character. The standard-error method for the first-stage (directed) coefficients. One of
"lm.vcov","lm.vcov.dfres","gamma"or"none". Default is"lm.vcov.dfres"for continuous data and"gamma"for categorical data. The"gamma"method requiresiv_samplestats = TRUE. When the model contains simple equality constraints among the directed coefficients (e.g. equal factor loadings), the"lm.vcov"/"lm.vcov.dfres"methods use a variance-weighted restricted-2SLS covariance for the constrained coefficients (as in the MIIVsem package); setiv_vcov_stage1 = "gamma"to obtain the delta-method (moment-Jacobian) standard errors instead.iv_vcov_stage2:Character. The standard-error method for the second-stage (undirected) parameters. One of
"h2","delta"or"none". Default is"h2". The"h2"method requiresiv_samplestats = TRUE.iv_vcov_gamma_modelbased:Logical. If
TRUE(the default), the normal-theory weight matrix (gamma) used for the standard errors is based on the model-implied covariance matrix; ifFALSE, it is based on the unrestricted (H1) sample covariance matrix.iv_gamma:Character. The covariance matrix of the sample statistics (gamma) used for the standard errors with complete continuous data. If
"nt"(the default), the normal-theory version is used. If"adf", the distribution-free (ADF) version is used: the standard errors of all the parameters are then delta-method standard errors (iv_vcov_stage1is set to"gamma"), and the default test statistic is"browne.residual.adf". The ADF version is the default if sampling weights are used, and it is implied byse = "robust". It requires the raw data andiv_samplestats = TRUE, and it is not (yet) available in combination with external instruments. This argument is ignored for categorical data (always ADF) and for two-stage missing data.iv_mean_structure:Character. How the free mean-structure parameters (observed intercepts and latent means) are estimated. With
"wls"(the default) they are obtained by a joint GLS solve that fits the model-implied means to the sample means across all groups, pooling parameters that are constrained equal across groups (e.g. intercepts for scalar invariance); this matches the maximum likelihood mean estimates (given the model-implied covariance matrix). With"moments"the intercepts are recomputed per equation and shared intercepts are pooled by a (simpler) nobs-weighted average. The two agree unless intercepts are constrained across groups (scalar invariance). This argument is ignored for categorical data, where the thresholds, intercepts and latent means (if any) are solved jointly from the sample thresholds and the means of the numeric variables.iv_vcov_jack_numerical,iv_vcov_jaca_numerical,iv_vcov_jacb_numerical:Logical. If
TRUE, the corresponding Jacobians used in the standard-error computation are obtained numerically rather than from analytic expressions. The default isFALSE; these are mainly intended for checking the analytic derivatives.iv_mimic_ml:Logical. If
FALSE(the default), the IV estimator uses unbiased divisors: the sample covariance matrix is divided byN-1(sample_cov_rescale = FALSE) and the per-equation residual variances (the RSS terms entering the standard errors and the Sargan test) use theN-Pdivisor. IfTRUE, the maximum likelihood divisorNis used throughout: the sample covariance is rescaled to the ML divisorNand the residual variances use theNdivisor as well. As a result, for just-identified models the IV point estimates and standard errors match the ML solution exactly.
Specifying instruments manually (the |~ operator)
By default lavaan determines the model-implied instruments for each equation
automatically. The |~ operator overrides this choice for a specific
equation: the left-hand side is the dependent variable of the equation (for a
latent variable, its scaling indicator), and the right-hand side lists the
instruments to use.
model <- '
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem60 ~ ind60
# use only x2 and x3 as instruments for the
# dem60 ~ ind60 equation
y1 |~ x2 + x3
'
fit <- sem(model, data = PoliticalDemocracy, estimator = "IV")
This is useful when the automatically selected instruments are weak (see
iv_weak above) or when subject-matter knowledge suggests a different
set of instruments.
External instruments. The instruments listed on the right-hand side of
|~ need not be part of the model. If an instrument is an observed
variable that does not otherwise appear in the model (it is not an indicator,
a predictor, an outcome, or otherwise mentioned), it is treated as an
external instrument: it is read from the data so that its covariances
with the model variables are available to the 2SLS estimator, but it never
enters the model-implied summary statistics. The model degrees of freedom, the
fit measures, and the model-implied moments are therefore exactly the same as
if the instrument had not been mentioned; only the equations for which it is
used are affected. External instruments require raw data (a data=
argument); they are not available when only sample moments are supplied. For
categorical data the external instruments must themselves be ordered
(categorical); the augmented polychoric correlations and the asymptotic
covariance of the sample statistics are then used for the estimates and the
standard errors. Single-group and multiple-group categorical models are
supported, but (for now) not equality constraints among the directed
coefficients (e.g. measurement invariance) together with external instruments.
## z is not part of the model; it is used only as an
## instrument for the (endogenous) regression y ~ x
model <- '
y ~ x
y |~ z
'
fit <- sem(model, data = Data, estimator = "IV")
For external instruments the point estimates and the directed-coefficient (loading and regression) standard errors are the usual 2SLS quantities. The second-stage (residual variance and covariance) standard errors also account for the sampling variability of the instrument moments: the directed coefficients depend on the instrument-model covariances, and this uncertainty is propagated into the variance/covariance parameters through the full (augmented) moment Jacobian.
Missing data
For continuous data with missing values, the IV estimator defaults to a
two-stage (FIML) approach: the saturated mean vector and covariance matrix are
estimated by the EM algorithm, the model is then estimated from these moments,
and the standard errors are corrected for the additional uncertainty stemming
from the EM estimates (Savalei & Bentler, 2009). This default is used when the
data contain missing values and the user does not set the missing
argument; missing = "ml" is interpreted as a request to handle
missing values and mapped to "two.stage" as well. Set
missing = "robust.two.stage" for sandwich-corrected
standard errors (Savalei & Falk, 2014), or missing = "listwise" to
delete incomplete cases instead. Two-stage missing-data estimation is also
available for multiple-group models.
Robust standard errors and sampling weights
For complete continuous data, the default standard errors and the default
test statistic are based on normal theory. Setting se = "robust" (or
estimator_args = list(iv_gamma = "adf")) replaces the normal-theory
covariance matrix of the sample statistics by the distribution-free (ADF)
version: the standard errors are then robust against non-normality, and the
default test statistic is Browne's residual-based ADF statistic
(test = "browne.residual.adf").
If sampling weights are used (the sampling_weights argument), the
parameters are estimated from the weighted sample statistics, and the ADF
version (which then reflects the sampling weights) is used by default; the
normal-theory standard errors ignore the sampling weights and are too small.
For categorical data, the standard errors and the test statistic are always
based on the (weighted) ADF covariance matrix of the sample statistics.
Multiple groups and measurement invariance
Multiple-group models are supported, with point estimates and standard errors
for continuous, two-stage-missing and categorical data. Cross-group equality
constraints are imposed in the usual way, either through shared parameter
labels in the model syntax or through the group_equal argument, so the
standard measurement-invariance sequence is available: configural
(group_equal = NULL), metric (group_equal = "loadings") and
scalar (group_equal = c("loadings", "intercepts")).
A parameter that is constrained equal across groups is estimated by pooling the
information from all groups; for a configural model the per-group estimates (and
their standard errors) reproduce the separate single-group fits. The mean
structure (observed intercepts and latent means) is estimated by a joint GLS
solve over all groups (see iv_mean_structure), which reproduces the
maximum likelihood mean estimates given the model-implied covariance matrix.
Inspecting the instruments and the Sargan test
Several lavInspect fields are specific to IV estimation:
lavInspect(fit, "iv"):(aliases
"miiv","instruments") a per-equation table with the dependent variable (lhs), the regressors (rhs), the observed variables actually used (lhs_new,rhs_new), the equation type (type:"miiv","ols"or"user"), and the instruments (iv) for that equation.lavInspect(fit, "sargan"):a per-equation table with the overidentification tests: the degrees of freedom (
df), the classical Sargan statistic (sargan.stat) and its p-value (sargan.pval), and the robust Browne residual-based statistic (browne.stat) and its p-value (browne.pval); seeiv_sarganabove. For categorical data the classical Sargan p-value isNA(not valid), so use thebrowne.*columns. Adjusted p-values (sargan.pval.adjandbrowne.pval.adj) are added wheniv_sargan_adjustis set.lavInspect(fit, "hansen")is an alias. Wheniv_method = "LIML"or"FULLER", the 2SLS first-order conditions no longer hold and the classical Sargan form is replaced by the Anderson & Rubin (1949) likelihood-ratio statisticN \log(\hat\lambda), where\hat\lambdais the minimized LIML variance ratio (the smallest eigenvalue of the LIML problem; Fuller uses the same\hat\lambda). This is the maximum likelihood chi-square statistic of the single-equation instrumental-variables regression model (y ~ x,x ~ z,y ~~ x) fitted with the normal likelihood. It is reported in columnslr.statandlr.pvalwith the same degrees of freedom.lavInspect(fit, "eqs"):the underlying per-equation information.
References
Anderson, T. W., & Rubin, H. (1949). Estimation of the parameters of a single equation in a complete system of stochastic equations. The Annals of Mathematical Statistics, 20(1), 46-63.
Bollen, K. A. (1996). An alternative two stage least squares (2SLS) estimator for latent variable equations. Psychometrika, 61(1), 109-121.
Fuller, W. A. (1977). Some properties of a modification of the limited information estimator. Econometrica, 45(4), 939-953.
Maydeu-Olivares, A., Fisher, Z. F., Bollen, K. A., & Rosseel, Y. (2026). Model-implied instrumental variables with many instruments: LIML estimation and goodness-of-fit testing. Working paper.
Bollen, K. A., & Maydeu-Olivares, A. (2007). A polychoric instrumental variable (PIV) estimator for structural equation models with categorical variables. Psychometrika, 72(3), 309-326.
Browne, M. W. (1984). Asymptotically distribution-free methods for the analysis of covariance structures. British Journal of Mathematical and Statistical Psychology, 37(1), 62-83.
Sargan, J. D. (1958). The estimation of economic relationships using instrumental variables. Econometrica, 26(3), 393-415.
Savalei, V., & Bentler, P. M. (2009). A two-stage approach to missing data: Theory and application to auxiliary variables. Structural Equation Modeling, 16(3), 477-497.
Savalei, V., & Falk, C. F. (2014). Robust two-stage approach outperforms robust full information maximum likelihood with incomplete nonnormal data. Structural Equation Modeling, 21(2), 280-302.
Staiger, D., & Stock, J. H. (1997). Instrumental variables regression with weak instruments. Econometrica, 65(3), 557-586.
See Also
lavaan, sem, lavOptions,
lavInspect.
Examples
## The classic Bollen (1989) Political Democracy example
model <- '
# measurement model
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem65 =~ y5 + y6 + y7 + y8
# regressions
dem60 ~ ind60
dem65 ~ ind60 + dem60
'
## fit using MIIV-2SLS instead of maximum likelihood
fit <- sem(model, data = PoliticalDemocracy, estimator = "IV")
summary(fit)
## the model-implied instruments used for each equation
lavInspect(fit, "iv")
## the per-equation Sargan overidentification tests
lavInspect(fit, "sargan")
## pass estimator options via estimator = list(...)
fit2 <- sem(model, data = PoliticalDemocracy,
estimator = list(estimator = "IV",
iv_varcov_method = "2RLS",
iv_sargan_adjust = "BH",
iv_weak = "warn"))
lavInspect(fit2, "sargan")
## LIML instead of 2SLS (less finite-sample bias with many instruments);
## the per-equation overidentification test is then the Anderson-Rubin
## likelihood-ratio statistic N log(lambda)
fit.liml <- sem(model, data = PoliticalDemocracy,
estimator = list(estimator = "IV", iv_method = "LIML"))
lavInspect(fit.liml, "sargan")
## Fuller-LIML with the default c = 1
fit.fuller <- sem(model, data = PoliticalDemocracy,
estimator = list(estimator = "IV", iv_method = "FULLER"))
## specify instruments manually with the |~ operator:
## use only x2, x3 as instruments for the dem60 ~ ind60 equation
model.iv <- '
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem60 ~ ind60
y1 |~ x2 + x3
'
fit3 <- sem(model.iv, data = PoliticalDemocracy, estimator = "IV")
lavInspect(fit3, "iv")
## Not run:
## equality constraints are honored (here: equal loadings across factors)
model.eq <- '
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + a*y2 + b*y3 + c*y4
dem65 =~ y5 + a*y6 + b*y7 + c*y8
dem60 ~ ind60
dem65 ~ ind60 + dem60
'
fit4 <- sem(model.eq, data = PoliticalDemocracy, estimator = "IV")
coef(fit4)
## multiple groups: metric measurement invariance (equal loadings)
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit.metric <- sem(HS.model, data = HolzingerSwineford1939, estimator = "IV",
group = "school", group_equal = "loadings")
summary(fit.metric)
## End(Not run)
James-Stein (Conditional Expectation) Estimation
Description
Estimate a structural equation model by replacing the latent variables in
each equation by an estimate of their conditional expectation given
observed proxies, followed by least squares (Burghgraeve, De Neve &
Rosseel, 2021). Two variants are available: the scaling James-Stein
estimator (estimator = "JS"), which conditions on the
marker/scaling indicators, and the aggregated James-Stein estimator
(estimator = "JSA"), which conditions on reliability-weighted
aggregates of the indicators. This page documents how to invoke the
estimators, the options that can be passed via the
estimator = list() argument, and the current restrictions.
Details
Like the instrumental-variable estimator (see
estimator_iv), the James-Stein estimators work
equation-by-equation: each measurement and structural equation is
estimated separately, the method is non-iterative, and no starting values
are needed. The two approaches differ in how the latent variables are
replaced by observable quantities. Where MIIV-2SLS projects on
instrumental variables, the James-Stein estimators regress on an estimate
of the conditional expectation of the latent variables given observed
proxies: E(eta | y1) = R y1 + (I - R) E(eta), where R is
the estimated reliability matrix of the proxies (a James-Stein type
shrinkage estimator). For the scaling variant the proxies are the
marker/scaling indicators; for the aggregated variant they are weighted
sums of the indicators, with reliability-maximizing (alphamax; Bentler,
1968) weights. Regressing on these conditional expectations is
algebraically identical to correcting the least-squares normal equations
for the measurement-error variance of the proxies, so the estimates are a
closed-form function of the sample moments (no raw data are needed: the
model can also be fitted from sample.cov and sample.nobs).
The measurement-error variances of the indicators are estimated by a
Spearman-type communality estimator, applied per factor: the communality
of an indicator is the average of the tetrads S[i,a] S[i,b] / S[a,b]
over pairs of other variables a, b. Only the tetrads that the
model structure declares admissible are averaged: a tetrad identifies the
communality of i when i is a pure indicator of the
factor (a single loading, no regressors) and the model implies no
association between any two of i, a and b other
than through the factor (the pairs are d-separated by the factor in the
path diagram). This excludes pairs with a residual covariance, and pairs
of indicators with cross-loadings or regressors whose extra variables
are connected without passing through the factor; it keeps, for
example, a pair of cross-loading indicators when the factor mediates
between their extra factors. Factors with three or more indicators use
the admissible within-factor tetrads; when an indicator has none (for
instance 2-indicator factors), the tetrads are formed with external
variables (observed model variables outside the factor), which requires
the factor to be correlated with other variables in the model. This
also covers a single-indicator factor whose reliability is identified
through the structural model; by the default lavaan rules, however, the
residual variance of a single indicator is fixed to zero, and a
model-fixed residual variance always takes precedence. The residual
variances can also be supplied directly (see js_theta below).
The communality of an indicator with a cross-loading or a regressor is
not identified by any tetrad; such indicators are never used as
conditioning proxies (see Details), so their reliability is not
needed.
The estimator is selected by setting estimator = "JS" (scaling) or
estimator = "JSA" (aggregated), for example
fit <- sem(model, data = Data, estimator = "JS")
Estimation proceeds in two stages. In the first stage, the directed
effects (factor loadings and regression coefficients) are estimated
equation-by-equation by least squares on the conditional expectations. In
the second stage, the undirected effects (residual variances and
covariances) are estimated by a weighted least-squares step applied to the
residual moments, exactly as for the IV estimator (see
js_varcov_method). When meanstructure = TRUE, the
marker-intercepts-zero parameterization is used
(marker_int_zero = TRUE: the latent means are free and equal the
population means of their scaling indicators), and all free mean
parameters are re-estimated by a joint GLS solve (see
js_mean_structure).
Simple equality constraints (e.g. equal factor loadings) and general
linear equality constraints (e.g. a == 2*b) among the directed
coefficients are honored by a pooled (system) solve. Multiple groups are
supported, including cross-group equality constraints for measurement
invariance testing (e.g. group_equal = c("loadings",
"intercepts")). Without cross-group constraints, the per-group estimates
and standard errors are identical to those of separate single-group fits.
Estimator options
Options specific to the JS/JSA estimators are passed as named elements of
a list to the estimator argument, alongside the estimator name:
fit <- sem(model, data = Data,
estimator = list(estimator = "JS",
js_varcov_method = "ULS",
js_gamma = "adf"))
The option names use snake_case. For backward compatibility, dot.case
names (e.g. js.varcov.method) are also accepted and silently
converted.
js_small_sample:Logical. If
TRUE(the default), the Efron-Morris small-sample factor(n-3)/(n-1)is applied to the estimated measurement-error variances in the shrinkage step, as in Burghgraeve et al. (2021). IfFALSE, the plain attenuation correction is used.js_theta:Character. How the measurement-error (residual) variances of the indicators are estimated.
"spearman"(the default) uses the Spearman-type communality estimator per factor (admissible within-factor tetrads; external tetrads when an indicator has none, for instance in 2-indicator factors; model-fixed residual variances take precedence for factors with fewer than 3 indicators);"user"takes the values fromjs_theta_values. The same estimator (and the same threejs_theta*options) provides the initial residual variances of theestimator = "MGM"procedure.js_theta_values:Named numeric vector. The residual variances of the indicators (on the same scale as the analyzed sample moments), used when
js_theta = "user". This makes it possible to plug in externally known reliabilities.js_theta_bounds:Character. Bounds applied to the Spearman communality estimates:
"wide"(the default),"standard"or"none". In addition, the resulting residual variances are always kept within[0, var(y)].js_lambda_floor:Character or numeric. The barrier that keeps the disattenuated proxy matrix of each equation away from singularity (see
Details)."se"(the default) truncates the measurement-error correction of an equation when the smallest rootlambdaof its proxy pencil is not more than two standard errors (on the log scale) above 1, with1/(n-1)as minimal margin; a nonnegative number is used as a fixed margin onlambda - 1;"none"disables the barrier.js_varcov_method:Character. The second-stage method used to estimate the residual variances and covariances. One of
"ULS","GLS","2RLS","RLS"or"NONE". Default is"RLS"(reweighted least squares). If"NONE", the variance/covariance parameters are not estimated.js_gamma:Character. The asymptotic covariance matrix of the sample moments (Gamma) used in the standard errors:
"nt"(normal-theory; the default) or"adf"(asymptotically distribution-free; requires complete raw data).js_vcov_gamma_modelbased:Logical. If
TRUE(the default), the normal-theory Gamma is evaluated at the model-implied covariance matrix; ifFALSE(or when the model-implied matrix is not positive definite), the unrestricted (h1) sample covariance matrix is used.js_mean_structure:Character. How the free mean parameters (observed intercepts and latent means) are estimated when
meanstructure = TRUE:"wls"(the default) re-estimates them jointly by GLS, which also provides the means of the exogenous latent variables;"moments"keeps the per-equation intercepts.js_jacobian:Character. How the Jacobian of the estimation map (needed for the delta-method standard errors) is computed:
"analytic"(the default) or"numeric"(numerical differentiation of the complete map; much slower for larger models). A few configurations are not covered by the analytic Jacobian (general linear equality constraints among the variance/covariance parameters, a non-positive-definite or non-converged second-stage weight matrix); these fall back to the numerical Jacobian automatically.
Standard errors and test statistics
By default (se = "standard"), delta-method standard errors are
computed by differentiating the complete estimation map with respect to
the sample moments, and combining the resulting Jacobian with the
asymptotic covariance matrix of the moments (js_gamma). The
Jacobian is computed analytically in a single chain-rule sweep (see
js_jacobian), so the standard errors are non-iterative as well.
Because the Jacobian runs through all estimation steps, the additional
variability caused by estimating the reliability matrix (Theorem 2 in
Burghgraeve et al., 2021) – and, for JSA, the aggregation weights – is
accounted for automatically. The full covariance matrix of the parameter
estimates is available, so defined parameters (:=) obtain proper
delta-method standard errors. The summary() header reports the
method (Delta) and the flavor of the moment covariance
(Gamma matrix: NT, ADF or TS). Setting
se = "robust" is a shortcut for the ADF flavor
(js_gamma = "adf"), which equals the infinitesimal-jackknife
(sandwich) covariance of the estimator. Alternatively,
se = "bootstrap" computes bootstrap standard errors, and
se = "none" skips the standard errors.
There is no discrepancy-function chi-square statistic; the default test
statistic is Browne's (1984) residual-based test
(test = "browne.residual.nt"; the ADF version can be requested
instead), and the fit measures reported by fitMeasures()
are based on it. Likelihood-based quantities (logl, AIC, BIC) are not
available. Modification indices are not available (as for the IV
estimator).
Missing data
By default, cases with missing values are removed listwise. When the data
contain missing values, missing = "two.stage" is selected
automatically (it can also be requested explicitly, as can
missing = "robust.two.stage"; missing = "ml" is interpreted
as a request to handle missing values and mapped to
"two.stage"): the saturated (EM) moments are used
for point estimation, and the standard errors are based on the two-stage
moment covariance (Savalei & Bentler, 2009; Savalei & Falk, 2014). The
test statistic then uses the model-based variant
("browne.residual.nt.model").
Residual covariances
Residual covariances among the indicators (including covariances that involve a scaling indicator) are supported: each equation conditions on a clean proxy set, i.e. observed variables whose residuals are uncorrelated with the residual of the equation's dependent variable (and with each other). When a default proxy (the scaling indicator, or an aggregate member) is invalidated by a residual covariance, it is replaced by (an aggregate of) clean pure indicators of the same factor, scaled by their estimated loadings – the James-Stein analog of dropping contaminated instruments in MIIV estimation. Contaminated correlations are likewise excluded from the Spearman reliability estimates. The residual covariances themselves are estimated in the second stage. This requires enough clean pure indicators: every needed reliability must have at least one admissible tetrad, and every equation needs at least one clean pure proxy per latent regressor; an informative error is raised otherwise. In particular, a scaling indicator with a cross-loading or a regressor cannot serve as a proxy for its factor, so the factor needs another pure indicator with an estimable reliability.
Small samples: the barrier on the disattenuation
In every equation, the kernel subtracts the measurement-error variances
of the proxies from their covariance matrix before solving the normal
equations (a Fuller-type attenuation correction). With two or more latent
regressors and small samples, the corrected matrix can be near-singular
or indefinite even when its population counterpart is comfortably
positive definite; the slopes of that equation then explode (estimates
and standard errors of order 10 to 100). The same device as in the local
SAM approach (the lambda_correction of sam) guards
against this, per equation: let lambda be the smallest root of
|S_zz - lambda * c * Theta_z| = 0, the largest multiple of the
error variances that can be subtracted before the matrix becomes
singular. When lambda - 1 is smaller than a margin, the
correction is truncated: the error variances are multiplied by
lambda - margin (at least 0) instead of 1, which shrinks the
equation toward ordinary least squares. By default
(js_lambda_floor = "se") the margin is a noise guard of two
standard errors of log(lambda) (delta method over the sample
moments), with 1/(n-1) as minimum: the barrier is an exact no-op
whenever lambda is comfortably above 1 (in practice at moderate
sample sizes), and only engages in the samples where the data do not
support the full disattenuation. A note reports the equations where the
multiplier dropped below 0.95; the per-equation values (lambda,
its standard error, the margin and the multiplier) are stored in the
fitted object (fit@internal$eqs, element js_lambda). The standard
errors condition on the truncation (the multiplier is held fixed in the
Jacobian). For an equation with a single latent regressor the pencil
root is the inverse of the proxy's unreliability, so the barrier engages
only when the proxy's reliability is not significantly above zero.
Restrictions
The JS/JSA estimators currently require: continuous data (no ordered
categorical variables), single-level models, a marker/scaling indicator
for every latent variable (std_lv = TRUE is not supported), a
recursive structural part (no feedback loops), and no higher-order
factors. The disturbance of a dependent variable may not be correlated
with (an ancestor of) one of its regressors. Exogenous observed
covariates are supported (they are part of the conditioning set of each
equation; note that fixed_x is set to FALSE).
References
Burghgraeve, E., De Neve, J., & Rosseel, Y. (2021). Estimating structural equation models using James-Stein type shrinkage estimators. Psychometrika, 86(1), 96-130.
Bentler, P. M. (1968). Alpha-maximized factor analysis (alphamax): Its relation to alpha and canonical factor analysis. Psychometrika, 33(3), 335-345.
Bollen, K. A. (1996). An alternative two stage least squares (2SLS) estimator for latent variable equations. Psychometrika, 61(1), 109-121.
Browne, M. W. (1984). Asymptotically distribution-free methods for the analysis of covariance structures. British Journal of Mathematical and Statistical Psychology, 37(1), 62-83.
Savalei, V., & Bentler, P. M. (2009). A two-stage approach to missing data: Theory and application to auxiliary variables. Structural Equation Modeling, 16(3), 477-497.
Savalei, V., & Falk, C. F. (2014). Robust two-stage approach outperforms robust full information maximum likelihood with incomplete nonnormal data. Structural Equation Modeling, 21(2), 280-302.
See Also
lavaan, sem, estimator_iv,
lavOptions, lavInspect.
Examples
## a CFA example
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data = HolzingerSwineford1939, estimator = "JS")
summary(fit, fit_measures = TRUE)
## the aggregated variant
fit.a <- cfa(HS.model, data = HolzingerSwineford1939, estimator = "JSA")
coef(fit.a)
## a full structural equation model
model <- '
# measurement model
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem65 =~ y5 + y6 + y7 + y8
# regressions
dem60 ~ ind60
dem65 ~ ind60 + dem60
'
fit2 <- sem(model, data = PoliticalDemocracy, estimator = "JS")
summary(fit2)
## pass estimator options via estimator = list(...)
fit3 <- sem(model, data = PoliticalDemocracy,
estimator = list(estimator = "JS",
js_varcov_method = "ULS",
js_gamma = "adf"))
## Not run:
## multiple groups: metric measurement invariance (equal loadings)
fit.metric <- cfa(HS.model, data = HolzingerSwineford1939,
estimator = "JS",
group = "school", group_equal = "loadings")
summary(fit.metric)
## End(Not run)
Fit Measures for a Latent Variable Model
Description
This function computes a variety of fit measures to assess the global fit of a latent variable model.
Usage
## S4 method for signature 'lavaan'
fitMeasures(object, fit_measures = "all",
baseline_model = NULL, h1_model = NULL,
fm_args = list(standard_test = "default",
scaled_test = "default",
rmsea_ci_level = 0.90,
rmsea_close_h0 = 0.05,
rmsea_notclose_h0 = 0.08,
robust = TRUE,
cat_nonpd = "na"),
output = "vector", level = NULL, ...)
## S4 method for signature 'lavaan'
fitmeasures(object, fit_measures = "all",
baseline_model = NULL, h1_model = NULL,
fm_args = list(standard_test = "default",
scaled_test = "default",
rmsea_ci_level = 0.90,
rmsea_close_h0 = 0.05,
rmsea_notclose_h0 = 0.08,
robust = TRUE,
cat_nonpd = "na"),
output = "vector", level = NULL, ...)
Arguments
object |
An object of class |
fit_measures |
If |
baseline_model |
If not NULL, an object of class
|
h1_model |
If not NULL, an object of class |
fm_args |
List. Additional options for certain fit measures. DEPRECATED.
The options should now be specified in the |
output |
Character. If |
level |
Only used for multilevel models. If not |
... |
Further arguments passed to or from other methods. Not currently
used for |
Details
For models with a casewise likelihood (data-defined, ":~",
parameters estimated by an external backend; random slopes), no test
statistic and no (comparable) saturated model exist, and only the
log-likelihood based measures are available: "npar",
"ntotal", "logl", "aic", "bic" and
"bic2" (plus "scaling.factor.h0" for random slopes with
robust standard errors). Requesting any other measure is an error.
For two-level models, "srmr_within" and "srmr_between" are
based on the residual correlations (the difference between the unrestricted
and the model-implied correlation matrix) of each level. The alternative
versions "srmr_within_mplus" and "srmr_between_mplus" follow
the definition used by Mplus (version 8.1 and later): the diagonal elements
are the relative variance residuals, the mean residuals are included (the
means of the variables that are split belong to the between level), and
the elements that only involve fixed exogenous covariates are not counted.
If mimic = "Mplus", these are also the values that are reported as
"srmr_within" and "srmr_between".
When a scaled (or robust) test statistic is requested (for example, by using
test = "satorra.bentler"), the function will also return fit indices
based on the scaled chi-square statistic, rather than the standard version.
These scaled versions of fit measures, such as CFI and RMSEA, are calculated in
the same way as their standard counterparts, with the key difference being that
the scaled chi-square statistic is used in place of the regular one. In the
output of fitMeasures(), these appear with the .scaled suffix,
or in the Scaled column of the summary() output.
However, this substitution-based approach—used in SEM software for many
years—has since been shown to be incorrect. Improved versions of robust fit
indices have been proposed, offering better theoretical properties. Although
still under development and not yet implemented for all estimation settings,
these improved robust fit measures are provided when available. They appear
with a .robust suffix in the output of fitMeasures(), or in the
Scaled column of the summary() output on a row labeled
Robust. As a general recommendation, these newer robust versions should
be used whenever available, in preference to the older scaled ones. See the
references below for more details.
It is also worth noting that, for models involving ordered categorical data,
robust fit indices are only computed if the underlying matrix of tetrachoric or
polychoric correlations is positive definite. If this condition is not
met—which is not uncommon in small samples—the robust measures are reported
as NA. In addition, these robust fit indices are based on the fit of
the model to the tetrachoric or polychoric correlations only, where the
thresholds are assumed to be free and unrestricted. If the model imposes
restrictions on the thresholds (for example, thresholds that are constrained
to be equal across groups in a measurement invariance setting), or if the
scaling factors or residual variances of the ordered indicators are free
parameters, the robust measures are reported as NA (with a warning).
In these settings, the scaled versions are still available.
Finally, in some situations (especially when the data contains missing values),
computing these robust fit indices may be computationally intensive. To avoid
long runtimes, the calculation of robust fit measures can be disabled by
setting the robust argument to FALSE in the fit_measures list.
FMG p-values can be selected through the existing standard_test
mechanism, for example
fitMeasures(fit, "pvalue", fm_args = list(standard_test = "peba4")).
No separate FMG-specific fit-measure names are needed.
For models fitted with sam using a local sam_method
("local", "fsr" or "cfsr"), the fit measures are
computed for the step-2 structural model only, conditional on the (fixed)
measurement model of step 1; loglikelihood-based measures (aic, bic, ...)
are not available. If sam_method = "global", the fit measures are
based on the joint model; since the parameters were estimated using a
two-step procedure, they should be interpreted with caution.
Value
A named numeric vector of fit measures (or a list, a matrix, or a
pretty-printed text version, depending on the output argument).
If all (default) fit measures are requested (and output is not
"list"), or if output = "text", the result carries two
(hidden) attributes that record
which test statistic(s) the fit measures are based on (intended for
developers): "standard.test" (always present; e.g.
"standard" or "browne.residual.nt.model"), and
"scaled.test" (only present if a scaled test statistic was used;
e.g. "satorra.bentler"). Before 0.7-3, "standard.test"
was only set if the test was not "standard". If an explicit
subset of fit measures is requested (e.g. fitMeasures(fit, "cfi")),
the (vector or matrix) result has no attributes (other than the names),
as before.
References
Ryu, E., & West, S. G. (2009). Level-specific evaluation of model fit in multilevel structural equation modeling. Structural Equation Modeling, 16(4), 583–601. doi:10.1080/10705510903203466
Brosseau-Liard, P. E., Savalei, V., & Li, L. (2012). An investigation of the sample performance of two nonnormality corrections for RMSEA. Multivariate behavioral research, 47(6), 904-930. doi:10.1080/00273171.2012.715252
Brosseau-Liard, P. E., & Savalei, V. (2014). Adjusting incremental fit indices for nonnormality. Multivariate behavioral research, 49(5), 460-470. doi:10.1080/00273171.2014.933697
Savalei, V. (2018). On the computation of the RMSEA and CFI from the mean-and-variance corrected test statistic with nonnormal data in SEM. Multivariate behavioral research, 53(3), 419-429. doi:10.1080/00273171.2018.1455142
Savalei, V. (2021). Improving fit indices in structural equation modeling with categorical data. Multivariate Behavioral Research, 56(3), 390-407. doi:10.1080/00273171.2020.1717922
Savalei, V., Brace, J. C., & Fouladi, R. T. (2023). We need to change how we compute RMSEA for nested model comparisons in structural equation modeling. Psychological Methods. doi:10.1037/met0000537
Zhang, X., & Savalei, V. (2023). New computations for RMSEA and CFI following FIML and TS estimation with missing data. Psychological Methods, 28(2), 263-283. doi:10.1037/met0000445
Foldnes, N., Moss, J., & Gronneberg, S. (2024). Improved goodness of fit procedures for structural equation models. Structural Equation Modeling: A Multidisciplinary Journal, 1-13. doi:10.1080/10705511.2024.2372028
Foldnes, N., Gronneberg, S., & Moss, J. (2026). Penalized eigenvalue block averaging: Extension to nested model comparison and Monte Carlo evaluations. Behavior Research Methods, 58(4). doi:10.3758/s13428-026-02968-4
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data = HolzingerSwineford1939)
fitMeasures(fit)
fitMeasures(fit, "cfi")
fitMeasures(fit, c("chisq", "df", "pvalue", "cfi", "rmsea"))
fitMeasures(fit, c("chisq", "df", "pvalue", "cfi", "rmsea"),
output = "matrix")
fitMeasures(fit, c("chisq", "df", "pvalue", "cfi", "rmsea"),
output = "text")
fitMeasures(fit, "pvalue", fm_args = list(standard_test = "peba4"))
## specify another threshold for RMSEA confidence interval
fitMeasures(fit, list(
fit_measures = c("cfi", "rmsea"),
rmsea_ci_level = 0.95))
## fit a more restricted model
fit0 <- cfa(HS.model, data = HolzingerSwineford1939, orthogonal = TRUE)
## Calculate RMSEA_D (Savalei et al., 2023)
## See https://psycnet.apa.org/doi/10.1037/met0000537
fitMeasures(fit0, "rmsea", h1_model = fit)
## level-specific fit measures for a multilevel model (Ryu & West, 2009)
model <- '
level: 1
fw =~ y1 + y2 + y3
fw ~ x1 + x2 + x3
level: 2
fb =~ y1 + y2 + y3
fb ~ w1 + w2
'
fit2l <- sem(model, data = Demo.twolevel, cluster = "cluster")
fitMeasures(fit2l, c("chisq", "df", "pvalue", "cfi", "rmsea",
"srmr_within"), level = "within")
fitMeasures(fit2l, c("chisq", "df", "pvalue", "cfi", "rmsea",
"srmr_between"), level = "between")
Fit Growth Curve Models
Description
Fit a Growth Curve model. Only useful if all the latent variables in the model
are growth factors. For more complex models, it may be better to use the
lavaan function.
Usage
growth(model = NULL, data = NULL, ordered = NULL, aux = NULL, sampling_weights = NULL,
sample_cov = NULL, sample_mean = NULL, sample_th = NULL,
sample_nobs = NULL, group = NULL, cluster = NULL, panel = NULL,
constraints = "", wls_v = NULL, nacov = NULL, ov_order = "model",
sampling_weights_cluster = NULL, ...)
Arguments
model |
A description of the user-specified model. Typically, the model
is described using the lavaan model syntax. See
|
data |
An optional data frame containing the observed variables used in the model. If some variables are declared as ordered factors, lavaan will treat them as ordinal variables. |
ordered |
Character vector. Only used if the data is in a data.frame. Treat these variables as ordered (ordinal) variables, if they are endogenous in the model. Importantly, all other variables will be treated as numeric (unless they are declared as ordered in the data.frame.) Since 0.6-4, ordered can also be logical. If TRUE, all observed endogenous variables are treated as ordered (ordinal). If FALSE, all observed endogenous variables are considered to be numeric (again, unless they are declared as ordered in the data.frame.) |
aux |
Character vector. Names of auxiliary observed variables, used to
make the missing-at-random (MAR) assumption more plausible under missing
data (continuous data only). With |
sampling_weights |
A variable name in the data frame containing
sampling weight information. Depending on the
|
sample_cov |
Numeric matrix. A sample variance-covariance matrix. The rownames and/or colnames must contain the observed variable names. For a multiple group analysis, a list with a variance-covariance matrix for each group. |
sample_mean |
A sample mean vector. For a multiple group analysis, a list with a mean vector for each group. |
sample_th |
Vector of sample-based thresholds. For a multiple group analysis, a list with a vector of thresholds for each group. |
sample_nobs |
Number of observations if the full data frame is missing and only sample moments are given. For a multiple group analysis, a list or a vector with the number of observations for each group. |
group |
Character. A variable name in the data frame defining the groups in a multiple group analysis. |
cluster |
Character. A (single) variable name in the data frame defining the clusters in a two-level dataset. |
panel |
Character. If the data are long panel data (one row per
person and occasion), the names of the id and the time variable, as in
|
constraints |
Additional (in)equality constraints not yet included in the
model syntax. See |
wls_v |
A user provided weight matrix to be used by estimator |
nacov |
A user provided matrix containing the elements of (N times)
the asymptotic variance-covariance matrix of the sample statistics.
For a multiple group analysis, a list with an asymptotic
variance-covariance matrix for each group. See the |
ov_order |
Character. If |
sampling_weights_cluster |
A variable name in the data frame containing
the sampling weights of the clusters (level-2 units). Only used for
two-level models (see the |
... |
Many more options can be specified, using 'name = value'.
See |
Details
The growth function is a wrapper for the more general
lavaan function, using the following default arguments:
meanstructure = TRUE,
int_ov_free = FALSE, int_lv_free = TRUE,
auto_fix_first = TRUE (unless std_lv = TRUE),
auto_fix_single = TRUE, auto_var = TRUE,
auto_cov_lv_x = TRUE, auto_efa = TRUE,
auto_th = TRUE, auto_delta = TRUE,
auto_cov_y = TRUE, and auto_cov_rv = TRUE (unless
mimic = "Mplus").
Value
An object of class lavaan, for which several methods
are available, including a summary method.
References
Yves Rosseel (2012). lavaan: An R Package for Structural Equation Modeling. Journal of Statistical Software, 48(2), 1-36. doi:10.18637/jss.v048.i02
See Also
lavaan, estimator_iv, estimator_js
Examples
## linear growth model with a time-varying covariate
model.syntax <- '
# intercept and slope with fixed coefficients
i =~ 1*t1 + 1*t2 + 1*t3 + 1*t4
s =~ 0*t1 + 1*t2 + 2*t3 + 3*t4
# regressions
i ~ x1 + x2
s ~ x1 + x2
# time-varying covariates
t1 ~ c1
t2 ~ c2
t3 ~ c3
t4 ~ c4
'
fit <- growth(model.syntax, data = Demo.growth)
summary(fit)
Register an external estimation backend
Description
Register a backend that estimates models lavaan prepares but does not
estimate itself, so that it can be named in the backend argument
of lavaan(), sem(), cfa(), ... (see
lavOptions). lavBackends() lists the registered
backends.
Usage
lavBackendRegister(name, fun, package = NULL, version = NULL,
supports = "all", capabilities = list(),
description = "", overwrite = TRUE)
lavBackends()
Arguments
name |
Character. The name of the backend, as used in the
|
fun |
A function |
package |
Character. The package that provides the backend, if
any. It is loaded (with |
version |
Character. A version string, shown by
|
supports |
Character vector. The model classes the backend handles:
|
capabilities |
List. Free-form capabilities of the backend (for example whether it returns a vcov, casewise log-likelihoods, or scores); stored with the descriptor for use by lavaan or by the backend. |
description |
Character. A one-line description. |
overwrite |
Logical. If |
Details
The backend option is a string resolved through this registry, so
that a call, a saved object, update() and parallel code all carry
a name rather than an R closure. For interactive use, a bare function
can be passed as backend; lavaan registers it under an anonymous
name ("function#1", ...) for the session.
Value
lavBackendRegister() invisibly returns the descriptor (a list).
lavBackends() returns a data frame with one row per registered
backend.
See Also
lavImportResults, lavOptions,
model.syntax.
Examples
# a tiny backend: casewise ML by nlminb(), for the moderated-slope model
# y ~ b*x, b :~ b0 + b1*data(z)
cw_backend <- function(object, args) {
pt <- parTable(object)
dat <- lavInspect(object, "data")
z <- object@Data@aux[[1]][, match("z", object@Data@ov.names.aux[[1]])]
y <- dat[, "y"]; x <- dat[, "x"]; n <- length(y)
free_rows <- which(pt$free > 0L)[order(pt$free[pt$free > 0L])]
par_names <- pt$plabel[free_rows] # y~~y, y~1, b0, b1
m2ll <- function(p) {
mu <- p[2] + (p[3] + p[4] * z) * x
sum((y - mu)^2) / p[1] + n * log(2 * pi * p[1])
}
opt <- nlminb(c(1, 0, 0, 0), m2ll, lower = c(1e-4, -Inf, -Inf, -Inf))
list(est = setNames(opt$par, par_names),
vcov = 2 * solve(optimHess(opt$par, m2ll)),
loglik = -opt$objective / 2,
converged = opt$convergence == 0L,
iterations = opt$iterations)
}
lavBackendRegister("nlminb_cw", cw_backend, supports = "dv",
description = "casewise ML by nlminb (toy)")
lavBackends()
set.seed(1)
n <- 200
z <- rnorm(n); x <- rnorm(n)
y <- 3 + (0.5 + 0.3 * z) * x + rnorm(n)
dat <- data.frame(y = y, x = x, z = z)
fit <- sem(' y ~ b * x
b :~ b0 + b1 * data(z) ', data = dat, backend = "nlminb_cw")
summary(fit)
Bootstrapping a Lavaan Model
Description
Bootstrap the LRT, or any other statistic (or vector of statistics) you can extract from a fitted lavaan object.
Usage
lavBootstrap(object, R = 1000L, type = "ordinary", verbose = FALSE,
fun = "coef", keep_idx = FALSE,
parallel = c("no", "multicore", "snow"),
ncpus = min(2L, max(1L, parallel::detectCores() - 2L, na.rm = TRUE)),
cl = NULL, iseed = NULL, h0_rmsea = NULL, method = "refit",
guard = TRUE, guard_tol = 0.25, ...)
bootstrapLavaan(object, R = 1000L, type = "ordinary", verbose = FALSE,
fun = "coef", keep_idx = FALSE,
parallel = c("no", "multicore", "snow"),
ncpus = min(2L, max(1L, parallel::detectCores() - 2L, na.rm = TRUE)),
cl = NULL, iseed = NULL, h0_rmsea = NULL, ...)
Arguments
object |
An object of class |
R |
Integer. The number of bootstrap draws. The lower-case
spelling |
type |
If |
fun |
A function which when applied to the |
... |
Other named arguments for |
verbose |
If |
keep_idx |
If |
parallel |
The type of parallel operation to be used (if any). If
missing, the default is |
ncpus |
Integer: number of processes to be used in parallel operation.
By default, this is 2 (following CRAN policy). You may set this to a higher
value (for example, the number of cores as detected by
|
cl |
An optional parallel or snow cluster for use if
|
iseed |
An integer to set the seed. Or NULL if no reproducible results are
needed. This works for both serial (non-parallel) and parallel settings.
Internally, |
h0_rmsea |
Only used if |
method |
Character. If |
guard |
Logical. Only used if |
guard_tol |
Numeric. Only used if |
Details
The fun function can return either a scalar or a numeric vector.
This function can be an existing function (for example coef) or
can be a custom defined function. For example:
myFUN <- function(x) {
# require(lavaan)
modelImpliedCov <- fitted(x)$cov
vech(modelImpliedCov)
}
If parallel="snow", it is imperative that the require(lavaan)
is included in the custom function.
When the fitted model was estimated with clustered or multilevel data (i.e., a
cluster= argument was used), the bootstrap automatically switches to a
cluster bootstrap: instead of resampling individual observations, whole
(level-2) clusters are resampled with replacement, keeping all level-1
observations within a selected cluster together. The number of clusters is held
fixed (equal to the number of clusters in the original data), while the total
number of observations may vary from one bootstrap sample to the next. A cluster
that is drawn more than once is treated as several distinct clusters. This
resampling scheme preserves the within-cluster dependence and is the
appropriate bootstrap both for two-level models and for single-level models with
cluster-robust standard errors. It is currently only available for a single
cluster (level-2) variable, and the "bca" confidence interval type
(in parameterEstimates) is not supported in this case.
When the fitted model contains rotated exploratory factors (EFA or ESEM; that
is, the model syntax uses the efa() modifier together with a
rotation= method other than "none"), bootstrap standard errors and
confidence intervals (requested via se = "bootstrap" when fitting the
model) are computed for the rotated solution. Each bootstrap sample is
refit and rotated, and its factors are then aligned (reordered and reflected) to
the original (full-sample) rotated solution before their variability is used.
This alignment resolves the rotational indeterminacy (the sign and order of the
exploratory factors), which would otherwise inflate the standard errors. Note
that the raw bootstrap coefficients returned by lavBootstrap(object,
fun = "coef") are not aligned to a reference solution in this way.
If method is "ij" or "hoij2", the model is not refitted
for the bootstrap samples; the bootstrap draws are approximated instead. See
the section ‘Approximate bootstrap methods’ below.
Value
For lavBootstrap(), the bootstrap distribution of the value(s)
returned by fun, when the object can be simplified to a vector.
Approximate bootstrap methods
Refitting the model for every bootstrap sample can take a long time. The
methods "ij" and "hoij2" avoid (most of) these refits. They
are requested with the method argument of lavBootstrap(), or,
when fitting the model, by using se = "bootstrap" together with,
for example, bootstrap = list(R = 1000, method = "ij") or
bootstrap = list(R = 1000, method = "hoij2", guard_tol = 0.1). The
draws are stored in the same way as the refitted draws, so that everything
that is based on them (standard errors, the confidence intervals of
parameterEstimates and standardizedSolution,
including those for defined parameters, and lavInspect(object,
"coef_boot")) works in the same way. The same bootstrap samples are used
as for method = "refit" (given the same iseed, and no
parallelization). Only the ordinary (nonparametric) bootstrap of the
parameter estimates (fun = "coef") is supported.
The infinitesimal jackknife (method = "ij")
A bootstrap sample is
equivalent to giving each observation a (multinomial) weight, and the
estimates are a smooth function of these weights. The infinitesimal jackknife
(IJ) approximates this function by a first-order Taylor expansion around the
original (unit) weights, using the casewise scores and the observed
information matrix of the original fit. The covariance matrix of the IJ draws equals (up to Monte
Carlo error) the Huber-White (sandwich) covariance matrix; the draws are
therefore mostly useful to obtain percentile-type confidence intervals for
(nonlinear) functions of the parameters. Because the approximation is linear
in the weights, it does not capture any skewness that is due to the
estimator itself (for example, for variance parameters in small samples).
If the data
are clustered (cluster = ), whole clusters are resampled (as for
method = "refit"); the covariance matrix of the IJ draws then equals
the cluster-robust sandwich covariance matrix. See the subsections below
for the models and settings that are supported.
The second-order infinitesimal jackknife (method = "hoij2")
A second-order term is added to the expansion (the second-order infinitesimal jackknife, or HOIJ-2). This term accounts for the change in the curvature of the objective function, both due to the reweighting of the observations and due to the change in the parameter values. As a result, the draws can also reflect the skewness of the estimator itself. The second-order term needs four evaluations of the gradient for every bootstrap sample, which is still much cheaper than refitting the model. Note that HOIJ-2 is a local (quadratic) approximation: it is usually closer to the refitted estimates than IJ for typical bootstrap samples, but it can be less accurate for the most extreme bootstrap samples, and these samples determine the limits of percentile-type confidence intervals.
The guard
Because the most extreme bootstrap samples matter most for confidence
intervals, a guard is used by default for method = "hoij2"
(guard = TRUE). For every bootstrap sample, the gradient of the
objective function is evaluated at the approximate draw, using the sample
statistics of that bootstrap sample. If the draw were exact, this gradient
would be zero. The size of the gradient is converted to an estimate of the
distance between the draw and the exact solution, expressed in standard
error units (the root mean square over the parameters). If this distance
exceeds guard_tol, the model is refitted for this bootstrap sample,
and the approximate draw is replaced by the refitted one. In large samples
and for well-behaved models, (almost) no bootstrap samples need a refit. In
small samples, or if the model is only weakly identified, many bootstrap
samples may need a refit, and the gain in speed is smaller; a note is given
if this happens for more than half of the bootstrap samples. The distances
and the indices of the refitted draws are available as the attributes
"dist" and "guard" of the returned matrix. The guard is not
perfect: the distance is itself an estimate, and a few inaccurate draws may
not be detected.
Scope (ML)
Both methods (IJ and HOIJ-2) are currently only
available for single-level models that are estimated by ML using continuous
data (complete, or incomplete with missing = "ml"), possibly with
multiple groups, sampling weights, clustered data (cluster bootstrap), and
(linear or nonlinear) equality constraints (including
ceq_simple = TRUE).
Bounds and linear inequality constraints are also allowed. Those
that are active in the original solution are treated as equality
constraints: the approximate draws stay on the boundary. For IJ, nothing
more is done: a parameter that is on its bound does not vary over the
draws. For HOIJ-2, the guard (see above) is used to correct this. Staying
on the boundary is not what happens in every bootstrap sample: in some samples, the solution leaves the
boundary, and in other samples, a bound or constraint that was not active
becomes active. The estimates are not a smooth function of the weights at
these transitions, and no Taylor expansion can describe them. The guard
of HOIJ-2 therefore also flags (and refits) every bootstrap sample for which the
approximate draw violates a bound or an inequality constraint, or for which
the sign of the Lagrange multiplier of an active bound or constraint
changes; the indices are available as the bound.idx element of the
"guard" attribute. If a bound is active, a substantial fraction of
the bootstrap samples is typically refitted. With guard = FALSE,
these draws are not corrected, and bounds or inequality constraints should
then not be combined with HOIJ-2. Nonlinear inequality constraints are not
supported for HOIJ-2.
DWLS and ULS (continuous or categorical data)
Both methods are also available for single-level models that are estimated
by DWLS or ULS, using complete continuous or categorical data (this includes
the estimators "WLSMV" and "ULSMV"); exogenous covariates,
sampling weights and ceq_simple = TRUE are not supported. For these
estimators, the parameter estimates are a function of the sample statistics
(means and covariances, or thresholds and polychoric correlations) and of a
weight matrix, and the approximation works in two stages. In the first
stage, the sample statistics of a bootstrap sample are approximated by a
first-order expansion, using the casewise influence values of these
statistics; the statistics themselves (for example, the polychoric
correlations) are not recomputed. The weight matrix is kept fixed (for ULS,
this is exact). In the second stage, the change in the parameters is
obtained from the change in the statistics by a first-order
(method = "ij") or a second-order (method = "hoij2")
expansion. The covariance matrix of the "ij" draws equals (up to
Monte Carlo error) the robust sandwich covariance matrix
(se = "robust.sem") with information_bread = "observed".
Note that "hoij2" is not a complete second-order expansion here: it
captures the nonlinearity of the model (the largest source of error), but
not the nonlinearity of the sample statistics, nor the changes in the
weight matrix. It is closer to the refitted estimates than "ij",
but less close than it is for ML. In addition, the guard only sees the
second stage: the distance is computed using the approximate sample
statistics, and it can not detect that these statistics themselves are
inaccurate for a bootstrap sample (for example, if a response category is
almost empty).
Which method to use?
-
"refit"is the reference: use it whenever the computing time is acceptable, and always in small samples or if the model is only weakly identified. -
"ij"costs (almost) nothing. Its standard errors are the robust (sandwich) standard errors, so its main use is to obtain percentile-type confidence intervals for (nonlinear) functions of the parameters, such as indirect effects or standardized parameters, in larger samples. -
"hoij2"(with the guard) is meant to replace the refit bootstrap if the latter is too slow: in larger samples almost no bootstrap samples need a refit, while in smaller samples the guard falls back on refitting where needed. The number of refitted draws is shown in the summary output.
BCa confidence intervals (boot_ci_type = "bca") are available for
both methods; the acceleration constants are then computed from the
influence values (see parameterEstimates).
Author(s)
Yves Rosseel. Ed Merkle contributed Yuan's bootstrap. Improvements to Yuan's bootstrap were contributed by Hao Wu and Chuchu Cheng. The handling of iseed was contributed by Shu Fai Cheung.
References
Bollen, K. and Stine, R. (1992) Bootstrapping Goodness of Fit Measures in Structural Equation Models. Sociological Methods and Research, 21, 205–229.
Yuan, K.-H., Hayashi, K., & Yanagihara, H. (2007). A class of population covariance matrices in the bootstrap approach to covariance structure analysis. Multivariate Behavioral Research, 42, 261–281.
Field, C. A., & Welsh, A. H. (2007). Bootstrapping clustered data. Journal of the Royal Statistical Society: Series B, 69, 369–390.
Giordano, R., Stephenson, W., Liu, R., Jordan, M. I., & Broderick, T. (2019). A Swiss army infinitesimal jackknife. Proceedings of the 22nd International Conference on Artificial Intelligence and Statistics (AISTATS), PMLR 89.
Giordano, R., Jordan, M. I., & Broderick, T. (2019). A higher-order Swiss army infinitesimal jackknife. arXiv:1907.12116.
Examples
# fit the Holzinger and Swineford (1939) example
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939, se="none")
# get the test statistic for the original sample
T.orig <- fitMeasures(fit, "chisq")
# bootstrap to get bootstrap test statistics
# we only generate 10 bootstrap samples in this example; in practice
# you may wish to use a much higher number
T.boot <- lavBootstrap(fit, R=10, type="bollen.stine",
fun = fitMeasures, fit_measures = "chisq")
# compute a bootstrap based p-value
pvalue.boot <- length(which(T.boot > T.orig))/length(T.boot)
# approximate the bootstrap draws, without refitting the model:
# a mediation model with an indirect effect
med.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9
speed ~ a*textual
visual ~ b*speed + c*textual
ab := a*b '
# first-order (infinitesimal jackknife)
fit.ij <- sem(med.model, data = HolzingerSwineford1939, se = "bootstrap",
bootstrap = list(R = 500, method = "ij"), iseed = 1234)
parameterEstimates(fit.ij)[25, ]
# second-order, with a guard that refits the model where needed
fit.h2 <- sem(med.model, data = HolzingerSwineford1939, se = "bootstrap",
bootstrap = list(R = 500, method = "hoij2"), iseed = 1234)
parameterEstimates(fit.h2)[25, ]
# the number of bootstrap samples that were refitted
length(attr(lavInspect(fit.h2, "coef_boot"), "guard")$refit.idx)
Compare measurement parameters across groups
Description
Side-by-side tables of the measurement parameters of a multiple-group model:
for every factor, its loadings in all groups (indicators in the rows, groups
in the columns), or the intercepts and thresholds of the indicators in all
groups. The range of every parameter over the groups is added, so that
(possibly) non-invariant items stand out. The function is meant for rotated
solutions (ESEM, with or without the agreement rotation, see
esem) and aligned models (see alignment), but
works for any multiple-group model.
Usage
lavCompareGroups(object, what = "loadings", standardized = FALSE,
add_range = TRUE, sort = FALSE)
Arguments
object |
An object of class |
what |
|
standardized |
Logical. If |
add_range |
Logical. If |
sort |
Logical. If |
Value
For what = "loadings", a named list with one data frame per factor
(the indicators in the rows, the groups in the columns); for what =
"intercepts", a single data frame (the indicators, or the thresholds of
the ordered indicators labelled item|threshold, in the rows). The
data frames are of class lavaan.data.frame.
See Also
lavTestAlignment for the invariance tests of an aligned
model; esem and alignment.
Examples
HS <- HolzingerSwineford1939
model <- ' efa("b")*f1 + efa("b")*f2 + efa("b")*f3 =~
x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 '
# the configural (per-group) rotation
fit <- cfa(model, data = HS, group = "school")
lavCompareGroups(fit)
## Not run:
# the agreement rotation: the solutions of the groups are made as similar
# as possible; what remains is (possibly) non-invariance
# (not run: the agreement rotation takes a while)
fit_a <- cfa(model, data = HS, group = "school",
rotation_args = list(mg_agreement = TRUE))
lavCompareGroups(fit_a, sort = TRUE)
lavCompareGroups(fit_a, standardized = TRUE)
## End(Not run)
Polychoric, polyserial and Pearson correlations
Description
Fit an unrestricted model to compute polychoric, polyserial and/or Pearson correlations.
Usage
lavCor(object, ordered = NULL, group = NULL, missing = "listwise",
ov_names_x = NULL, sampling_weights = NULL,
se = "none", test = "none",
estimator = "two.step", baseline = FALSE, ...,
cor_smooth = FALSE, cor_smooth_tol = 1e-04, output = "cor")
Arguments
object |
Either a |
ordered |
Character vector. Only used if |
group |
Only used if |
missing |
If |
sampling_weights |
Only used if |
ov_names_x |
Only used if |
se |
Only used if |
test |
Only used if output is |
estimator |
If |
baseline |
Only used if output is |
... |
Optional parameters that are passed to the |
cor_smooth |
Logical. Only used if |
cor_smooth_tol |
Numeric. Smallest eigenvalue used when reconstructing the correlation matrix after an eigenvalue decomposition. |
output |
If |
Details
This function is a wrapper around the lavaan function,
but where the model is defined as the unrestricted model. The
following free parameters are included: all covariances/correlations among
the variables, variances for continuous variables, means for continuous
variables, thresholds for ordered variables, and if exogenous variables
are included (ov_names_x is not empty) while some variables
are ordered, also the regression slopes enter the model.
Value
By default, if output = "cor" or output = "cov", a symmetric
matrix (of class "lavaan.matrix.symmetric", which only affects the
way the matrix is printed). If output = "th", a named vector of
thresholds. If output = "fit" or output = "lavaan",
an object of class lavaan.
References
Olsson, U. (1979). Maximum likelihood estimation of the polychoric correlation coefficient. Psychometrika, 44(4), 443-460.
Olsson, U., Drasgow, F., & Dorans, N. J. (1982). The polyserial correlation coefficient. Psychometrika, 47(3), 337-347.
See Also
Examples
# Holzinger and Swineford (1939) example
HS9 <- HolzingerSwineford1939[,c("x1","x2","x3","x4","x5",
"x6","x7","x8","x9")]
# Pearson correlations
lavCor(HS9)
# ordinal version, with three categories
HS9ord <- as.data.frame( lapply(HS9, cut, 3, labels = FALSE) )
# polychoric correlations, two-stage estimation
lavCor(HS9ord, ordered=names(HS9ord))
# thresholds only
lavCor(HS9ord, ordered=names(HS9ord), output = "th")
# polychoric correlations, with standard errors
lavCor(HS9ord, ordered=names(HS9ord), se = "standard", output = "est")
# polychoric correlations, full output
fit.un <- lavCor(HS9ord, ordered=names(HS9ord), se = "standard",
output = "fit")
summary(fit.un)
Indirect and Total Effects
Description
‘lavEffects’ computes various ‘effects’ that are functions of the estimated model parameters of a fitted lavaan object. In this version, the focus is on the classic (LISREL-style) total, indirect and direct effects among the variables that appear in the structural part of the model (that is, the variables that are involved in a regression). Both observed and latent variables are supported.
This avoids the need to pre-specify all indirect (and total) effects manually
in the model syntax (using the := operator), which can be tedious when
there are many of them.
Usage
lavEffects(object, effects = c("total", "indirect"),
se_def = NULL, level = 0.95, monte_carlo = NULL,
boot_ci_type = "perc", zstat = TRUE, pvalue = TRUE, ci = TRUE,
standardized = FALSE, cov_std = TRUE,
add_class = TRUE, output = "data.frame", ...)
Arguments
object |
An object of class |
effects |
Character vector. One or more of |
se_def |
Character (or If |
level |
Numeric. The confidence level for the confidence intervals. |
monte_carlo |
List (or |
boot_ci_type |
Character. Only used when |
zstat |
Logical. If |
pvalue |
Logical. If |
ci |
Logical. If |
standardized |
Logical, character vector, or vector of (observed) variable
names, behaving as in |
cov_std |
Logical. See |
add_class |
Logical. If |
output |
Character. If |
... |
Only old names of arguments - with dots - are allowed here. |
Details
All effects are derived from the reduced-form matrix
(I - B)^{-1}, where B is the matrix of (direct) regression
coefficients among the structural variables (the beta matrix in the
LISREL representation that lavaan uses internally). Writing B[i,j] for the
direct effect of variable j on variable i, we have:
the direct effect of
joniequalsB[i,j];the total effect of
joniequals\left((I - B)^{-1} - I\right)[i,j];the indirect effect of
joniequals the total effect minus the direct effect.
Only effects that are structurally non-zero (that is, for which a directed path
from j to i exists) are reported. For indirect effects, this means
that at least one path of length two or more must exist.
The delta and Monte Carlo methods only require the parameter estimates and the
estimated covariance matrix of the parameters. The delta method produces
(symmetric) normal-theory confidence intervals; the Monte Carlo method produces
percentile-based confidence intervals, which need not be symmetric around the
point estimate. The Monte Carlo method typically behaves better than the delta
method for effects that are products of parameters (such as indirect effects),
in particular in smaller samples. When the model was fitted with
se = "bootstrap", the bootstrap draws are reused to obtain bootstrap
standard errors and bootstrap percentile confidence intervals (this requires
no additional model fitting).
Models fitted with conditional_x = TRUE are also supported: in that
case the structural model is eta = B eta + Gamma x + zeta, where the
exogenous covariates x are stored in the gamma matrix. The effects
of these covariates on the endogenous variables are then computed as
(I - B)^{-1} Gamma (total), Gamma (direct) and
((I - B)^{-1} - I) Gamma (indirect), and reported alongside the effects
among the beta variables.
Value
If output = "data.frame" (the default), a data.frame (of class
lavaan.effects) with the following columns: effect (the type of
effect: total, indirect or direct), lhs (the outcome variable),
op (always "~"), rhs (the predictor variable), and,
depending on the arguments, group/level/block,
est, se, z, pvalue, ci.lower,
ci.upper and (if standardized is requested) one or more of
std.lv, std.all, std.nox and std.user. The effect
in a given row is the effect of rhs on lhs.
If output = "list", a (possibly nested) list of matrices, where element
[i,j] contains the effect of variable j on variable i.
See Also
parameterEstimates, standardizedSolution.
Examples
# a simple mediation model
set.seed(1234)
X <- rnorm(300)
M <- 0.5 * X + rnorm(300)
Y <- 0.4 * M + 0.3 * X + rnorm(300)
Data <- data.frame(X = X, Y = Y, M = M)
model <- ' # direct effect
Y ~ c*X
# mediator
M ~ a*X
Y ~ b*M
'
fit <- sem(model, data = Data)
# total and indirect effects, with Monte Carlo standard errors
lavEffects(fit)
# all effects, using the delta method
lavEffects(fit, effects = c("total", "indirect", "direct"), se_def = "delta")
# add standardized (total and indirect) effects
lavEffects(fit, se_def = "delta", standardized = TRUE)
lavaan Export
Description
Export a fitted lavaan object to an external program.
Usage
lavExport(object, target = "lavaan", prefix = "sem", dir_name = "lav_export",
export = TRUE, ...)
Arguments
object |
An object of class |
target |
The target program. Current options are |
prefix |
The prefix used to create the input files; the name of the input file has the pattern ‘prefix dot target dot in’; the name of the data file has the pattern ‘prefix dot target dot raw’. |
dir_name |
The directory name (including a full path) where the input files will be written. |
export |
If |
... |
Only to support old argument name 'dir.name'. |
Details
This function was mainly created to quickly generate an Mplus syntax file to
compare the results between Mplus and lavaan. The target "lavaan" can
be useful to create a full model syntax as needed for the lavaan()
function. More targets (perhaps for LISREL or EQS) will be added
in future releases.
Value
If export = TRUE, a directory (called lav_export by default) will
be created, typically containing a data file, and an input file so that the
same analysis can be run using an external program. If export = FALSE, a
character string containing the model syntax only for the target program.
See Also
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
out <- lavExport(fit, target = "Mplus", export=FALSE)
cat(out)
The unrestricted (H1) model
Description
Compute only the summary statistics of the unrestricted (H1) model: the
saturated mean vector and variance-covariance matrix (and thresholds, if
some variables are ordered) that normally end up in the @h1 slot
of a fitted lavaan object. Unlike sem or cfa,
no model is needed. If a model is provided anyway, it is only used to
determine the relevant variables, their role (exogenous, ordered,
per level, ...) and the data-related options, so that the result is
exactly the h1 information a fit of that model would use.
If the data are incomplete and missing = "ml" (fiml), the summary
statistics are the EM estimates of the saturated model; this is a
convenient way to obtain fiml estimates of standard descriptive
statistics. For multilevel data (using the cluster argument),
the within- and between-level summary statistics (and the intraclass
correlations) are computed.
Usage
lavH1(model = NULL, data = NULL, ordered = NULL, sampling_weights = NULL,
group = NULL, cluster = NULL, missing = "default",
ov_names_x = NULL, ov_names_l = list(),
estimator = "default", se = "default", test = "none", ...,
output = "list", wls_v = NULL, gamma = NULL, add_extra = TRUE,
add_labels = TRUE, add_class = TRUE, drop_list_single_group = TRUE)
Arguments
model |
Optional. Either a description of the user-specified model
(as in |
data |
A |
ordered |
Character vector declaring additional variables as ordered
(ordinal). Variables that are declared as ordered factors in the data
frame are always treated as ordinal. If |
sampling_weights |
A variable name in the data frame containing sampling weight information. |
group |
A variable name in the data frame defining the groups in a multiple group analysis. |
cluster |
A variable name in the data frame defining the clusters in a two-level dataset. |
missing |
How to handle missing data. If |
ov_names_x |
Character vector. Variables that need to be treated as exogenous. Only used if no model is provided. |
ov_names_l |
List. Only used for two-level data when no model is provided: the variable names per level. By default, all variables are used at both levels. |
estimator |
The estimator (see |
se |
Only used if |
test |
Only used if |
... |
Optional parameters that are passed to the
|
output |
Character. If |
wls_v |
Logical. If |
gamma |
Logical. If |
add_extra |
Logical. If |
add_labels |
Logical. If |
add_class |
Logical. If |
drop_list_single_group |
Logical. If |
Value
If output = "list" (the default), a list with the h1 summary
statistics (see the output argument above). If
output = "lavaan", a fitted lavaan object for
the unrestricted model; its summary() shows the standard errors,
Wald (z) statistics and p-values of the summary statistics (for
example, to flag significant correlations when
correlation = TRUE). The object may also serve as an ingredient
for two-stage estimation procedures. If output = "lavMoments", an
object of class lavMoments that can be passed directly as the
data= argument of lavaan/cfa/sem.
Reproducing a fit from an output = "lavMoments" object
A lavMoments object reproduces the original raw-data fit
exactly for the estimators whose estimates, standard errors and
test statistics are functions of the summary statistics only. This
includes maximum likelihood ("ML") and generalized least squares
("GLS"); the robust variants ("MLM", "MLMV",
"MLMVS", ... and the Satorra-Bentler / scaled-shifted /
mean-variance-adjusted tests), provided the gamma (nacov)
matrix is requested (gamma = TRUE); the diagonally weighted least
squares estimators for ordered data ("WLSMV", "WLSM",
"DWLS", ..., which include wls_v and nacov by
default); and two-stage maximum likelihood for incomplete continuous data
(missing = "two.stage" or "robust.two.stage").
For the estimators whose weight matrix is estimator-specific (for
example the identity weight of the "ULS" family, or the ADF weight
of continuous "WLS"), pass the SAME estimator to
lavH1() as will be used in the refit, so that the matching
wls_v is returned.
A raw-data fit cannot be reproduced from summary statistics when the
standard errors or test statistic depend on the individual cases: the
Huber-White ('robust') sandwich ("MLR", se =
"robust.huber.white"), the first-order/outer-product information
("MLF"), cluster-robust (cluster =) standard errors, the
bootstrap (se = "bootstrap"), pairwise maximum likelihood
("PML"), and direct full-information maximum likelihood for
incomplete data (missing = "ml"; use missing = "two.stage"
instead).
See Also
lavCor for (polychoric, polyserial and Pearson)
correlations (which uses the same machinery), and
lavInspect with what = "h1" to extract the h1
summary statistics from a fitted lavaan object.
Examples
# saturated summary statistics of the Holzinger & Swineford data
lavH1(HolzingerSwineford1939[, paste0("x", 1:9)])
# fiml (EM) estimates of the descriptive statistics with missing data
HS.missing <- HolzingerSwineford1939
HS.missing$x5[1:10] <- NA
lavH1(HS.missing[, paste0("x", 1:9)], missing = "ml")
# a model is accepted, but only determines the variables and options
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
h1 <- lavH1(HS.model, data = HolzingerSwineford1939, group = "school")
# the unrestricted model as a fitted lavaan object; summary() shows the
# standard errors, z-statistics and p-values of the summary statistics
fit.h1 <- lavH1(HolzingerSwineford1939[, paste0("x", 1:9)],
output = "lavaan")
summary(fit.h1)
# which correlations are significant?
fit.cor <- lavH1(HolzingerSwineford1939[, paste0("x", 1:9)],
output = "lavaan", correlation = TRUE)
summary(fit.cor)
# categorical data: extract all summary statistics (including wls_v and
# nacov), then (re)fit a model from the summary statistics only
Data <- HolzingerSwineford1939[, paste0("x", 1:9)]
Data[] <- lapply(Data, cut, breaks = 3, labels = FALSE)
Data[] <- lapply(Data, ordered)
model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
moments <- lavH1(model, data = Data, output = "lavMoments")
moments
fit <- cfa(model, data = moments) # identical to cfa(model, data = Data)
# two-stage ML for incomplete (continuous) data: the EM saturated moments
# plus the stage-1 nacov allow a moments-only refit to reproduce the exact
# two-stage estimates, standard errors and (scaled) test statistics
HS.incomplete <- HolzingerSwineford1939[, paste0("x", 1:9)]
HS.incomplete$x1[1:20] <- HS.incomplete$x5[15:40] <- NA
model2 <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6 '
moments2 <- lavH1(model2, data = HS.incomplete, missing = "two.stage",
output = "lavMoments")
fit2 <- cfa(model2, data = moments2)
# same as: cfa(model2, data = HS.incomplete, missing = "two.stage")
Import estimation results from an external backend
Description
Build a fitted lavaan object from a model that lavaan prepared
(with do_fit = FALSE) and the results of an estimation carried out
elsewhere, for example by an external package that estimates models with
data-defined (":~") parameters using a casewise likelihood. The
parameter estimates, standard errors, log-likelihood and convergence
information are placed in the object, so that summary(),
coef(), vcov(), parameterEstimates(),
logLik() and the other post-fit functions can be used.
Usage
lavImportResults(object, est, vcov = NULL, se = NULL, loglik = NULL,
converged = TRUE, iterations = NA_integer_,
backend = "external", status = NULL, nobs = NULL,
loglik_casewise = NULL, scores = NULL,
backend_object = NULL, ...)
Arguments
object |
An object of class |
est |
Numeric vector with the estimates of the free parameters.
Either a named vector, where the names are the plabels (the
|
vcov |
Optional variance-covariance matrix of the free parameters,
one row and column per free parameter. If the matrix has dimnames,
they are used (as for |
se |
Optional numeric vector with standard errors (named or in
free-parameter order, as for |
loglik |
Optional single number: the log-likelihood at the
estimates. Needed for |
converged |
Logical. Did the backend converge? |
iterations |
Integer. The number of iterations the backend used (if known). |
backend |
Character. The name of the backend; shown in the output. |
status |
Optional: the backend's own status code or message (stored verbatim). |
nobs |
Optional: the number of observations the backend used. If
given, it must match the number of observations lavaan retained (see
|
loglik_casewise |
Optional numeric vector with the casewise
log-likelihood contributions (returned by
|
scores |
Optional matrix with the casewise scores (one row per observation, one column per free parameter); stored for future use. |
backend_object |
Optional: the backend's own result object; stored
in the |
... |
Not used. |
Details
The object is rebuilt through lavaan's regular pipeline, with the
estimates as (fixed) starting values and without optimization, and the
slots that lavaan can not compute itself are then filled from the
supplied results. Before that, the estimates are checked against the
equality and inequality constraints of the model (a warning is given when
the backend did not honour them), vcov is checked for symmetry and
positive semi-definiteness, and the standard errors of defined
(":=") parameters are computed by the delta method.
For models with data-defined (":~") parameters, the log-likelihood
is the casewise one supplied by the backend, the moderated (host)
parameters have no scalar estimate (NA in the parameter table), and
everything derived from a single set of model-implied moments remains
unavailable (see the ‘Data-defined (moderated) parameters’ section
in model.syntax). For ordinary models, lavaan computes the
model-implied moments, the log-likelihood and the test statistics itself
from the imported estimates; the test option of object is
honoured, and since do_fit = FALSE sets it to "none" unless
a test was requested explicitly, request the test when preparing the
object (for example test = "standard").
Value
An object of class lavaan.
See Also
lavBackendRegister (let lavaan call the backend itself,
through the backend option), model.syntax,
lavInspect.
Examples
set.seed(1)
n <- 200
z <- rnorm(n); x <- rnorm(n)
y <- 3 + (0.5 + 0.3 * z) * x + rnorm(n)
dat <- data.frame(y = y, x = x, z = z)
model <- ' y ~ b * x
b :~ b0 + b1 * data(z) '
fit0 <- sem(model, data = dat, do_fit = FALSE)
pt <- parTable(fit0)
# a tiny external 'backend': casewise ML by nlminb()
free_rows <- which(pt$free > 0L)[order(pt$free[pt$free > 0L])]
par_names <- pt$plabel[free_rows] # .p2. (y~~y), .p4. (y~1), .p6. (b0), .p7. (b1)
m2ll <- function(p) {
mu <- p[2] + (p[3] + p[4] * z) * x
sum((y - mu)^2) / p[1] + n * log(2 * pi * p[1])
}
opt <- nlminb(c(1, 0, 0, 0), m2ll, lower = c(1e-4, -Inf, -Inf, -Inf))
est <- setNames(opt$par, par_names)
vc <- 2 * solve(optimHess(opt$par, m2ll))
fit <- lavImportResults(fit0, est = est, vcov = vc,
loglik = -opt$objective / 2,
iterations = opt$iterations, backend = "nlminb")
summary(fit)
logLik(fit)
Inspect or extract information from a fitted lavaan object
Description
The lavInspect() and lavTech() functions can be used to
inspect/extract information that is stored inside (or can be computed from) a
fitted lavaan object. Note: the (older) inspect() function is
now simply a shortcut for lavInspect() with default arguments.
Usage
## S3 method for class 'lavaan'
lavInspect(object, what = "free", add_labels = TRUE, add_class = TRUE,
list_by_group = TRUE,
drop_list_single_group = TRUE, ...)
## S3 method for class 'lavaan'
lavTech(object, what = "free", add_labels = FALSE, add_class = FALSE,
list_by_group = FALSE,
drop_list_single_group = FALSE, ...)
## S3 method for class 'lavaan'
inspect(object, what = "free", ...)
Arguments
object |
An object of class |
what |
Character. What needs to be inspected/extracted? See Details for a
full list. Note: the |
add_labels |
If |
add_class |
If |
list_by_group |
Logical. Only used when the output are model matrices.
If |
drop_list_single_group |
If |
... |
For |
Details
The lavInspect() and lavTech() functions only differ in the way
they return the results. The lavInspect() function will prettify the
output by default, while the lavTech() will not attempt to prettify the
output by default. The (older) inspect() function is a simplified
version of lavInspect() with only the first two arguments.
The keywords are case-insensitive, and dots and underscores are
interchangeable: "cov_lv", "cov.lv" and "COV_LV" all
select the same output. The snake_case spelling is used below; the dotted
spelling (used in older versions of lavaan, and in many existing scripts)
remains accepted. The component names inside the returned objects (for
example res.cov in the "sampstat" output) are not affected.
Below is a list of possible values for the what argument, organized
in several sections:
Model matrices:
"free":A list of model matrices. The non-zero integers represent the free parameters. The numbers themselves correspond to the position of the free parameter in the parameter vector. This determines the order of the model parameters in the output of, for example,
coef()andvcov()."partable":A list of model matrices. The non-zero integers represent both the fixed parameters (for example, factor loadings fixed at 1.0) and the free parameters (ignoring any equality constraints). They correspond to all entries (fixed or free) in the parameter table. See
parTable."se":A list of model matrices. The non-zero numbers represent the standard errors for the free parameters in the model. If two parameters are constrained to be equal, they will share the same standard error. Aliases:
"std_err"and"standard_errors"."se_std":A list of model matrices. The non-zero numbers represent the standard errors for the (completely) standardized free parameters in the model. Alias:
"std_se"."start":A list of model matrices. The values represent the starting values for all model parameters. Alias:
"starting_values"."est":A list of model matrices. The values represent the estimated model parameters. Aliases:
"estimates", and"x"."est_unrotated":A list of model matrices. The values represent the estimated model parameters before rotation was applied. Only relevant if rotation was used (for example in EFA); otherwise this is identical to
"est"."dx_free":A list of model matrices. The values represent the gradient (first derivative) values of the model parameters. If two parameters are constrained to be equal, they will have the same gradient value.
"dx_all":A list of model matrices. The values represent the first derivative with respect to all possible matrix elements. Currently, this is only available when the estimator is
"ML"or"GLS"."std":A list of model matrices. The values represent the (completely) standardized model parameters (the variances of both the observed and the latent variables are set to unity). Aliases:
"std_all","standardized"."std_lv":A list of model matrices. The values represent the standardized model parameters (only the variances of the latent variables are set to unity.)
"std_nox":A list of model matrices. The values represent the (completely) standardized model parameters (the variances of both the observed and the latent variables are set to unity; however, the variances of any observed exogenous variables are not set to unity; hence no-x.)
"mm_lambda":The estimated factor loading matrix (per group), as extracted from the
@GLISTslot. Alias:"lambda"."mm_delta":The estimated delta (scaling) matrix (per group), as extracted from the
@GLISTslot. Only available for categorical data or when a correlation structure is used. (Note: this is the delta model matrix, not the delta jacobian that is returned by"delta".)
To extract a single model matrix (from the @GLIST slot), use the
"mm_*" options (for example "mm_lambda" for the factor loading
matrix). For backward compatibility, the (older) bare names are still accepted
as aliases.
Information about the data:
"data":A matrix containing the observed variables that were used to fit the model. The matrix has no row or column names. The columns correspond to the output of
lav_object_vnames(object), while the rows correspond to the output oflavInspect(object, "case_idx")."ordered":A character vector. The ordered variables.
"nobs":Numeric vector. The effective number of observations in each group that were used in the analysis. If sampling weights were provided, this is the (per group) sum of the weights, consistent with the value returned by the
nobs()method. Use"norig"to obtain the number of rows in the data."norig":Integer vector. The original number of observations (rows in the data) in each group.
"ntotal":Numeric. The total effective number of observations that were used in the analysis. If there is just a single group, this is the same as the
"nobs"option; if there are multiple groups, this is the sum of the"nobs"numbers for each group. If sampling weights were provided, this is the sum of the weights."case_idx":Integer vector. The case/observation numbers that were used in the analysis. In the case of multiple groups: a list of numbers.
"empty_idx":The case/observation numbers of those cases/observations that contained missing values only (at least for the observed variables that were included in the model). In the case of multiple groups: a list of numbers.
"th_idx":Integer vector. For categorical data, the index of the observed variable that each threshold belongs to. In the case of multiple groups: a list of integer vectors.
"patterns":A binary matrix. The rows of the matrix are the missing data patterns where 1 and 0 denote non-missing and missing values for the corresponding observed variables respectively (or
TRUEandFALSEiflavTech()is used.) If the data is complete (no missing values), there will be only a single pattern. In the case of multiple groups: a list of pattern matrices."patterns_freq":Integer vector. The number of cases (rows in the data) per missing data pattern, in the same order as the rows of the
"patterns"matrix. If the data is complete, a single number (the number of observations). In the case of multiple groups: a list of integer vectors. Alias:"pattern_freq"."patterns_stats":The sample statistics per missing data pattern, as used by the full information maximum likelihood (FIML) and two-stage estimation methods. Only available if
missing = "ml","ml.x","two.stage"or"robust.two.stage". A list with one element per missing data pattern; each element is a list with the following components:cov(the covariance matrix of the observed variables in this pattern, divided by the number of cases),mean(the mean vector of the observed variables in this pattern),freq(the number of cases in this pattern; if sampling weights were used, the sum of the weights), andvar_idx(a logical vector indicating which observed variables are observed in this pattern). In the case of multiple groups: a list of such lists. Aliases:"pattern_stats","missing_stats"."response_patterns":The response patterns of the ordered (categorical) variables. A list with the following components:
pat(a matrix with one row per observed response pattern, sorted from the most to the least frequent pattern; the columns correspond to the ordered variables),freq(the number of cases per response pattern),npatterns(the number of observed response patterns),total_patterns(the number of possible response patterns), andempty_patterns(the number of possible response patterns that were not observed). Only available if the model contains ordered variables and raw data was used. In the case of multiple groups: a list of such lists. Alias:"resp_patterns"."coverage":A symmetric matrix in which each element contains the proportion of jointly observed data points for the corresponding pair of observed variables. In the case of multiple groups: a list of coverage matrices.
"sampling_weights":Numeric vector. The (normalized) sampling weights that were used in the analysis, one per case (in the order of
"case_idx"). Depending on thesampling_weights_normalizationoption, the weights are rescaled so that they sum to the number of observations within each group ("group", the default), to the total number of observations ("total"), or not at all ("none"). Only available if sampling weights were provided. In the case of multiple groups: a list of numeric vectors. Alias:"weights"."group":A character string. The group variable in the data.frame (if any).
"ngroups":Integer. The number of groups.
"group_label":A character vector. The group labels.
"level_label":A character vector. The level labels.
"cluster":A character vector. The cluster variable(s) in the data.frame (if any).
"nlevels":Integer. The number of levels.
"nclusters":Integer. The number of clusters that were used in the analysis.
"ncluster_size":Integer. The number of different cluster sizes.
"cluster_size":Integer vector. The number of observations within each cluster. For multigroup multilevel models, a list of integer vectors, indicating cluster sizes within each group.
"cluster_id":Integer vector. The cluster IDs identifying the clusters. For multigroup multilevel models, a list of integer vectors, indicating cluster IDs within each group.
"cluster_idx":Integer vector. The cluster index for each observation. The cluster index ranges from 1 to the number of clusters. For multigroup multilevel models, a list of integer vectors, indicating cluster indices within each group.
"cluster_label":Integer vector. The cluster ID for each observation. For multigroup multilevel models, a list of integer vectors, indicating the cluster ID for each observation within each group.
"cluster_sizes":Integer vector. The different cluster sizes that were used in the analysis. For multigroup multilevel models, a list of integer vectors, indicating the different cluster sizes within each group.
"average_cluster_size":Integer. The average cluster size (using the formula
s = (N^2 - sum(cluster.size^2)) / (N*(nclusters - 1L))). For multigroup multilevel models, a list containing the average cluster size per group.
Observed sample statistics:
"sampstat":Observed sample statistics. Aliases:
"obs","observed","samp","sample","samplestatistics". Since 0.6-3, we always check if an h1 slot is available (the estimates for the unrestricted model); if present, we extract the sample statistics from this slot. This implies that if the variables are continuous andmissing = "ml"(or"fiml"), we return the covariance matrix (and mean vector) as computed by the EM algorithm under the unrestricted (h1) model. If the h1 slot is not present (for example, because the model was fitted withh1 = FALSE), we return the sample statistics from the SampleStats slot. In that case, pairwise deletion is used for the elements of the covariance matrix (or correlation matrix), and listwise deletion for all univariate statistics (means, intercepts, and thresholds)."sampstat_std":Standardized observed sample statistics. The covariance matrix is rescaled to a correlation matrix. Aliases:
"obs_std","observed_std","samp_std","sample_std","samplestatistics_std"."sampstat_h1":Deprecated. Do not use any longer.
"var":Numeric vector. The observed variances of the observed variables: the diagonal of the covariance matrix returned by
"sampstat"(that is, the h1-based estimates if the h1 slot is available). Ifconditional_x = TRUE, the variances of the joint (y, x) sample covariance matrix are returned; use"res_var"to obtain the residual variances. In the case of multiple groups (or levels): a list of vectors. Alias:"sampstat_var"."res_var":Numeric vector. The residual variances of the (non-exogenous) observed variables, after conditioning on the exogenous covariates: the diagonal of the
res.covmatrix returned by"sampstat". Only available ifconditional_x = TRUE."icov":The inverse of the observed sample covariance matrix (as returned by
"sampstat"). In the case of multiple groups: a list of matrices. Not available for multilevel models. Alias:"sampstat_icov"."res_icov":The inverse of the residual sample covariance matrix (the
res.covmatrix returned by"sampstat"). Only available ifconditional_x = TRUE."cov_log_det":Numeric. The logarithm of the determinant of the observed sample covariance matrix (as returned by
"sampstat"). In the case of multiple groups: a numeric vector with one value per group. Not available for multilevel models. Alias:"sampstat_cov_log_det"."res_cov_log_det":Numeric. The logarithm of the determinant of the residual sample covariance matrix. Only available if
conditional_x = TRUE."res_th_nox":Numeric vector. For categorical data, the sample thresholds of the ordered variables, ignoring the exogenous covariates (that is, the thresholds of the marginal distribution of each ordered variable). If
conditional_x = TRUE, these differ from the (residual) thresholds returned by"sampstat"; if no covariates are used, they are identical to thethelement of"sampstat". In the case of multiple groups: a list of vectors. Alias:"th_nox"."wls_obs":The observed sample statistics (covariance elements, intercepts/thresholds, etc.) in a single vector.
"wls_v":The weight matrix as used in weighted least squares estimation. If the estimator is
"DWLS"or"ULS", only the diagonal is used, but a full (diagonal) matrix is returned."wls_vd":Numeric vector. The diagonal of the
"wls_v"weight matrix. For the"DWLS"and"ULS"estimators, this vector contains the (only) weights that are used in the estimation. In the case of multiple groups: a list of vectors."gamma":N times the asymptotic variance matrix of the sample statistics. Alias:
"sampstat_nacov"."group_w":Numeric vector. The observed group weights: the logarithm of the (effective) number of observations in each group. This is the same metric as the
group.welement of the"implied"and"sampstat"output (which is only shown ifgroup_w_free = TRUE). Alias:"group_weights"."logl":Numeric vector. The loglikelihood of the fitted model, per group (
NAif the estimator does not provide a loglikelihood). The sum over the groups is the value returned bylogLik(). Alias:"loglik"."h1_logl":Numeric vector. The loglikelihood of the unrestricted (h1) model, per group. The sum over the groups is the
unrestricted.loglfit measure. Only available if the h1 slot is available (h1 = TRUE, the default). Alias:"h1_loglik".
Model features:
"meanstructure":Logical.
TRUEif a meanstructure was included in the model."categorical":Logical.
TRUEif categorical endogenous variables were part of the model."fixed_x":Logical.
TRUEif the exogenous x-covariates are treated as fixed."parameterization":Character. Either
"delta"(the Delta parameterization) or"theta"(the Theta parameterization); the stored value is in lower case.
Model-implied sample statistics:
"implied":The model-implied summary statistics. Alias:
"fitted","expected","exp"."resid":The difference between observed and model-implied summary statistics. Alias:
"residuals","residual","res"."cov_lv":The model-implied variance-covariance matrix of the latent variables. Alias:
"veta"[for V(eta)]."cor_lv":The model-implied correlation matrix of the latent variables.
"mean_lv":The model-implied mean vector of the latent variables. Alias:
"eeta"[for E(eta)]."cov_ov":The model-implied variance-covariance matrix of the observed variables. Aliases:
"sigma","sigma_hat"."cor_ov":The model-implied correlation matrix of the observed variables.
"mean_ov":The model-implied mean vector of the observed variables. Aliases:
"mu","mu_hat"."cov_all":The model-implied variance-covariance matrix of both the observed and latent variables.
"cor_all":The model-implied correlation matrix of both the observed and latent variables.
"th":The model-implied thresholds. Alias:
"thresholds"."mm_theta":The (residual) variance-covariance matrix of the observed variables (the theta model matrix). Aliases:
"theta","theta_cov"."theta_cor":The (residual) variance-covariance matrix of the observed variables, expressed in correlation metric.
"wls_est":The model-implied sample statistics (covariance elements, intercepts/thresholds, etc.) in a single vector.
"vy":The model-implied unconditional variances of the observed variables.
"rsquare":The R-square value for all endogenous variables. Aliases:
"r-square","r2"."fs_determinacy":The factor determinacies (based on regression factor scores). They represent the (estimated) correlation between the factor scores and the latent variable scores.
"fs_reliability":The factor reliabilities (based on regression factor scores). They are the square of the factor determinacies.
"fs_determinacy_Bartlett":The factor determinacies (based on Bartlett factor scores). They represent the (estimated) correlation between the factor scores and the latent variable scores.
"fs_reliability_bartlett":The factor reliabilities (based on Bartlett factor scores). They are the square of the factor determinacies.
"icc":The intraclass correlation coefficients for clustered data with multilevel models. Computed from the model-implied (H1) within-group and between-group covariance matrices. Only available for models with clustered data and multiple levels.
"ranef":The random effects (empirical Bayes predictions of the cluster-level latent variables). Only available for clustered data (in the long format) with multiple levels.
"sampstat_2l":The intermediate (sufficient) sample statistics of the two-level data, as used by the multilevel estimation routines. A list with the following components:
sigma_wandmu_w(the pooled within-cluster covariance matrix, divided by the number of observations minus the number of clusters, and the within-level means),sigma_bandmu_b(the moment-based between-level covariance matrix and means, as used for starting values),s_b(the between covariance matrix of the cluster means),s(the average cluster size, see"average_cluster_size"),y1y1(the crossproduct matrix of the level-1 data),y2(the cluster means, one row per cluster),mean_dandcov_d(the mean vectors and covariance matrices of the cluster means, per cluster size, in the order of"cluster_sizes"; the between-only variables come first), andloglik_x(the loglikelihood contribution of the fixed exogenous covariates). Only available for multilevel models. In the case of multiple groups: a list of such lists. Aliases:"sampstat_twolevel","sampstat_cluster".
Diagnostics:
"mdist2_fs":The squared Mahalanobis distances for the (Bartlett) factor scores.
"mdist_fs":The Mahalanobis distances for the (Bartlett) factor scores.
"mdist2_resid":The squared Mahalanobis distances for the (Bartlett-based) casewise residuals.
"mdist_resid":The Mahalanobis distances for the (Bartlett-based) casewise residuals.
If (some of) the data is ordered categorical, the Mahalanobis distances are
generalized as in Mansolf and Reise (2017): each distance is replaced by its
expected value over the region of the (multivariate normally distributed)
latent response vector that is consistent with the observed response pattern,
approximated by Monte Carlo integration (set.seed() can be used for
reproducibility). Observed continuous variables are conditioned on, and
missing values are integrated out. Note that in this case
"mdist_fs"/"mdist_resid" return the expected distance
E[d] (the person-fit indices d_f^* and d_r^* of Mansolf
and Reise), while "mdist2_fs"/"mdist2_resid" return the
expected squared distance E[d^2], which is not the square of the
former.
Optimizer information:
"converged":Logical.
TRUEif the optimizer has converged;FALSEotherwise."iterations":Integer. The number of iterations used by the optimizer.
"optim":List. All available information regarding the optimization results.
"rstarts":List. The results of the random-start runs (only available if the model was fitted with
rstarts > 0). One element per run, containing the free parameter vector at the end of that run, with the attributesconverged(logical),fx(the value of the discrepancy function at the solution),start(the random starting values that were used) anditerations. A run that failed with an error is an all-NA vector withconverged = FALSEand the error message in theerrorattribute. Among the converged runs, the run with the smallestfxvalue is the one that provided the final solution (unless the initial run did better). Alias:"random_starts"."npar":Integer. Number of free parameters (ignoring constraints).
Rotation information (only if the model contains efa blocks and a rotation
was applied; the output is a list with one element per block (group and/or
level), or a single element if there is only one block and
drop_list_single_group = TRUE):
"rotation":List. Per block, a list with one element per efa block (named by the efa block label), containing all available information about the rotation of that set of factors: the names of the factors and indicators (
lv_names,ov_names), the rotationmethod, whether the rotation wasorthogonal, the row weights, thealgorithm, whether the algorithmconverged, the number ofiterations, the value of the rotationcriterionat the solution, the rotation matrixrot(rows: the unrotated factors; columns: the rotated factors in their final order; the rotated loadings areA %*% rotfor an orthogonal rotation andA %*% solve(t(rot))for an oblique rotation, withAthe unrotated loadings), the covariance matrixphiof the rotated factors (a correlation matrix, except whenmg_agreement = TRUE, see"rotation_matrix"below), the column permutationorderapplied to the rotated solution (order[k]is the column of the rotated solution placed in positionk; seeorder_lv_by), and the random starts (starts, see"rotation_starts"below). For a multiple-group model withmg_agreement = TRUE,criterion,convergedanditerationsrefer to the joint (agreement) rotation, whilegroup_criterion,group_converged,group_iterationsandstartsrefer to the per-group rotation that provided its starting point, andmg_agreement_scalestells how the scale of each factor was split over the groups (seeesem); with the alignment of the intercepts (mg_agreement_intercepts),meansholds the aligned factor means of the group;mg_agreement_reference_groupis the reference group, andscales_starts(scales-only mode) the loss value and convergence of every random start over the scales and means. For a model withalignment = "fixed"or"free"(seealignment), thealignmentelement holds the aligned variances and means of the group, the loss value, the reference group and the random starts. Alias:"rotation_info"."rotation_matrix":List. Per block, the rotation matrix
Hfor all latent variables of the block (the identity for the latent variables outside the efa blocks): the rotated model matrices arelambda %*% solve(t(H)),t(H) %*% psi %*% H,t(H) %*% beta %*% solve(t(H))andt(H) %*% alpha, wherelambda,psi,betaandalphaare the unrotated model matrices (see"est_unrotated"). The column permutation and the sign reflections are included inH; for a multiple-group model withmg_agreement = TRUE, so is the rescaling of the rotated factors to equal column sums of squares across groups (which is why the factor variances are not one in that case). Alias:"rot"."lv_order":List. Per block, an integer vector with the order of the latent variables after rotation: element
kis the index of the column of the rotated solution that was placed in positionk(see theorder_lv_byoption). Alias:"rotation_order"."rotation_criterion":List. Per block, a numeric vector with the value of the rotation criterion at the solution, one per efa block. Alias:
"rotation_value"."rotation_converged":List. Per block, a logical vector indicating whether the rotation algorithm converged, one per efa block.
"rotation_starts":List. Per block and per efa block, the results of the random starts of the rotation algorithm (see the
rstartsoption):valueis the vector with the value of the rotation criterion at the end of each run (Inffor a run that failed or ended in a degenerate solution),iterationsandconvergedthe number of iterations and the convergence flag of each run, androtthe list with the corresponding rotation matrices (before the sign reflection and the column reordering). The run with the smallest value provided the solution. Comparing the values reveals whether the criterion has several local minima.NULLif no random starts were used. Alias:"rotation_rstarts".
Gradient, Hessian, observed, expected and first.order information matrices:
"gradient":Numeric vector containing the first derivatives of the discrepancy function with respect to the (free) model parameters.
"gradient_logl":Numeric vector containing the first derivatives of the loglikelihood with respect to the (free) model parameters.
"optim_gradient":Numeric vector containing the first derivatives of the objective function (as seen by the optimizer) with respect to the (free) model parameters.
"hessian":Matrix containing the second derivatives of the discrepancy function with respect to the (free) model parameters.
"information":Matrix containing either the observed or the expected information matrix (depending on the information option of the fitted model). This is unit-information, not total-information.
"information_expected":Matrix containing the expected information matrix for the free model parameters.
"information_observed":Matrix containing the observed information matrix for the free model parameters.
"information_first_order":Matrix containing the first.order information matrix for the free model parameters. This is the outer product of the gradient elements (the first derivative of the discrepancy function with respect to the (free) model parameters). Alias:
"first_order"."augmented_information":Matrix containing either the observed or the expected augmented (or bordered) information matrix (depending on the information option of the fitted model). Only relevant if constraints have been used in the model.
"augmented_information_expected":Matrix containing the expected augmented (or bordered) information matrix. Only relevant if constraints have been used in the model.
"augmented_information_observed":Matrix containing the observed augmented (or bordered) information matrix. Only relevant if constraints have been used in the model.
"augmented_information_first_order":Matrix containing the first.order augmented (or bordered) information matrix. Only relevant if constraints have been used in the model.
"inverted_information":Matrix containing either the observed or the expected inverted information matrix (depending on the information option of the fitted model).
"inverted_information_expected":Matrix containing the inverted expected information matrix for the free model parameters.
"inverted_information_observed":Matrix containing the inverted observed information matrix for the free model parameters.
"inverted_information_first_order":Matrix containing the inverted first.order information matrix for the free model parameters.
"h1_information":Matrix containing either the observed, expected or first.order information matrix (depending on the information option of the fitted model) of the unrestricted h1 model. This is unit-information, not total-information.
"h1_information_expected":Matrix containing the expected information matrix for the unrestricted h1 model.
"h1_information_observed":Matrix containing the observed information matrix for the unrestricted h1 model.
"h1_information_first_order":Matrix containing the first.order information matrix for the unrestricted h1 model. Alias:
"h1_first_order".
Variance covariance matrix of the model parameters:
"vcov":Matrix containing the variance covariance matrix of the estimated model parameters.
"vcov_std_all":Matrix containing the variance covariance matrix of the standardized estimated model parameters. Standardization is done with respect to both observed and latent variables.
"vcov_std_lv":Matrix containing the variance covariance matrix of the standardized estimated model parameters. Standardization is done with respect to the latent variables only.
"vcov_std_nox":Matrix containing the variance covariance matrix of the standardized estimated model parameters. Standardization is done with respect to both observed and latent variables, but ignoring any exogenous observed covariates.
"vcov_def":Matrix containing the variance covariance matrix of the user-defined (using the := operator) parameters.
"vcov_def_std_all":Matrix containing the variance covariance matrix of the standardized user-defined parameters. Standardization is done with respect to both observed and latent variables.
"vcov_def_std_lv":Matrix containing the variance covariance matrix of the standardized user-defined parameters. Standardization is done with respect to the latent variables only.
"vcov_def_std_nox":Matrix containing the variance covariance matrix of the standardized user-defined parameters. Standardization is done with respect to both observed and latent variables, but ignoring any exogenous observed covariates.
"vcov_def_joint":Matrix containing the joint variance covariance matrix of both the estimated model parameters and the defined (using the := operator) parameters.
"vcov_def_joint_std_all":Matrix containing the joint variance covariance matrix of both the standardized model parameters and the user-defined parameters. Standardization is done with respect to both observed and latent variables.
"vcov_def_joint_std_lv":Matrix containing the joint variance covariance matrix of both the standardized model parameters and the user-defined parameters. Standardization is done with respect to the latent variables only.
"vcov_def_joint_std_nox":Matrix containing the joint variance covariance matrix of both the standardized model parameters and the user-defined parameters. Standardization is done with respect to both observed and latent variables, but ignoring any exogenous observed covariates.
Constraint information (equality/inequality constraints, bounds). All matrices and vectors are reconstructed from the fitted model (the constraint functions are evaluated at the final parameter estimates), and are labeled so that rows correspond to individual constraints and columns to free parameters:
"constraints":List. All constraint information for the fitted model:
$ceq.jac(the Jacobian of the equality constraints, one row per constraint, evaluated at the final estimates),$ceq.rhs(right-hand side constants),$ceq.resid(the values of the equality constraint functions at the solution; all (near) zero),$ceq.rank(the number of linearly independent equality restrictions; this is the number subtracted from the parameter count in the degrees of freedom),$ceq.lambda(Lagrange multipliers, when available),$cin.jac,$cin.rhs,$cin.slack(the slack of each inequality constraint at the solution; (near) zero if the constraint is binding),$cin.active(logical;TRUEfor inequality constraints that were binding at the solution),$cin.lambda,$k(see"constraints_nullspace"below),$k0(offset vector; only non-NULLwhen the model contains only linear equality constraints, in which case any admissible parameter vector can be written astheta = k0 + K %*% theta.reduced), and$ceq.simple(logical;TRUEwhen simple equality constraints (a == b) were absorbed into the parameter vector (see theceq_simpleoption), so that the free parameter vector already satisfies them and$ceq.jacis empty). The inequality rows appear in this order: finite upper bounds, finite lower bounds, explicit"<"/">"constraints; all are written in slack form (the row value is nonnegative at an admissible point). Alias:"con"."constraints_jacobian":Matrix. The Jacobian of all constraints: the equality rows stacked above the inequality rows, evaluated at the final estimates. The attribute
"active"is a logical vector flagging, per row, whether the constraint was binding at the solution (equality rows are always active). Alias:"con_jac"."constraints_nullspace":Matrix. An orthonormal basis
Kof the null space of the equality-constraint Jacobian, as used by the standard error and (robust) test statistic machinery: post-multiplying the Jacobian of the model-implied sample statistics ("delta") byKrestricts it to the directions that satisfy the (linearized) equality constraints. For example, the information matrix of the constrained model in reduced form ist(K) %*% I %*% K, and its constrained (Moore-Penrose) inverse in the full parameter space isK %*% solve(t(K) %*% I %*% K) %*% t(K). If the model contains no equality constraints, the identity matrix is returned. The row names indicate the parameter space: they correspond to the free parameters, with one row per parameter-table row when simple equality constraints were absorbed (ceq_simple = TRUE). Aliases:"constraints_k","eq_constraints_k","con_k".
Miscellaneous:
"coef_boot":Matrix containing estimated model parameters for each bootstrap sample. Only relevant when bootstrapping was used.
"monte_carlo":Matrix containing the Monte Carlo draws of the model parameters, as used for the Monte Carlo confidence intervals of defined parameters (Preacher & Selig, 2012). Only relevant when these draws were requested. Aliases:
"mc","mc_coef","coef_mc"."UGamma":Matrix containing the product of 'U' and 'Gamma' matrices as used by the Satorra-Bentler correction. The trace of this matrix, divided by the degrees of freedom, gives the scaling factor.
"UfromUGamma":Matrix containing the 'U' matrix as used by the Satorra-Bentler correction. Alias:
"U"."delta":The delta matrix (per group): the Jacobian of the model-implied summary statistics (the rows: means, (co)variances, thresholds, ...) with respect to the free model parameters (the columns). This is the matrix used in the delta method. (Note: this is the delta Jacobian, not the delta model matrix that is returned by
"mm_delta".) In the case of multiple groups: a list of matrices."delta_rownames":The row names of the delta matrix (see
"delta"): the labels of the model-implied summary statistics. In the case of multiple groups: a list of character vectors."list":The parameter table. The same output as given by
parTable()."list_unmoderated":The parameter table of the ‘unmoderated’ model, for models with data-defined (
":~") parameters: the":~"definitions and their component parameters are removed, and the moderated parameters are ordinary free parameters again (see the ‘Data-defined (moderated) parameters’ section inmodel.syntax). For models without":~"definitions, the parameter table is returned unchanged. Alias:"partable_unmoderated"."fit":The fit measures. Aliases:
"fitmeasures","fit_measures","fit_indices". The same output as given byfitMeasures()."mi":The modification indices. Alias:
"modindices","modification_indices". The same output as given bymodindices()."loglik_casewise":Vector containing the casewise loglikelihood contributions. Only available if estimator =
"ML"."options":List. The option list.
"call":List. The call as returned by match.call, coerced to a list.
"timing":List. The timing (in milliseconds) of various lavaan subprocedures.
"test":List. All available information regarding the (goodness-of-fit) test statistic(s).
"baseline_test":List. All available information regarding the (goodness-of-fit) test statistic(s) of the baseline model.
"baseline_partable":Data.frame. The parameter table of the (internal) baseline model.
"post_check":Post-fitting check if the solution is admissible. A warning is raised if negative variances are found, or if
lavInspect(fit, "cov_lv"), thepsimatrix (as returned bylavInspect(fit, "est"); it also contains the residual (co)variances of the observed endogenous variables), orlavInspect(fit, "theta")is not positive (semi-)definite."zero_cell_tables":List. List of bivariate frequency tables where at least one cell is empty.
"iv":Data.frame. One row per (transformed) equation, with the (model-implied) instrumental variables that were used for each equation. Columns are
lhs,rhs,lhs.new,rhs.new,type, andinstruments. Only available whenestimator = "IV". Aliases:"ivs","miiv","miivs","instr","instruments". In the case of multiple groups: a list of data.frames."eqs":List. The (internal) list of equations that was used for the (MI)IV-based estimation, including the instruments, the coefficients, and the Sargan test per equation. Only available when
estimator = "IV"."sargan":Data.frame. The per-equation overidentification tests, for each overidentified equation. Columns are
lhs,rhs,df,sargan.stat,sargan.pval,browne.stat, andbrowne.pval. Thesargan.*columns are the classical Sargan test (assumes normality; the p-value isNAfor categorical data, where it is not valid); thebrowne.*columns are a robust residual-based test computed with the distribution-free (ADF) ACOV for continuous data or the polychoric ACOV for categorical data."hansen"is an alias. Only available whenestimator = "IV". In the case of multiple groups: a list of data.frames."sam_struc_fit_object":The (internal) step-2 structural model of a model fitted with
samusing a localsam.method("local","fsr"or"cfsr"): a lavaan object, fitted to the estimated latent (co)variances (and means) of step 1.fitMeasures(),lavResiduals()andmodindices()operate on this object when they are called with the sam object itself."sam_struc"is an alias."sam_attenuation":For a model fitted with
samusingsam_method = "local": the predicted small-sample attenuation of the latent correlations induced by the blockwise estimation of the measurement model (see the Details section ofsam). A list with the block terms (h, one per latent variable;NAwhen the prediction is not available for that factor), the sample size (n), the estimated latent correlations (cor), the (stabilized) curvature term of each pair (c), and the predicted relative (rel) and absolute (bias) small-sample bias of each correlation. When the plug-in correction was applied (local optionbias_correction = "plugin"), the list also contains the correction factors (factor), the cap (kappa), the shrinkage applied to keep the latent covariance matrix positive definite (shrink, 1 = none) and the corrected correlations (cor_corrected). In the case of multiple groups: a list of such lists."sam_atten"is an alias."version":The lavaan version number that was used to construct the fitted lavaan object.
See Also
lavaan, estimator_iv, estimator_js
Examples
# fit model
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data = HolzingerSwineford1939, group = "school")
# extract information
lavInspect(fit, "sampstat")
lavTech(fit, "sampstat")
Observed Variable Covariance Matrix from a Model and Data
Description
The lavaan model syntax describes a latent variable model. Often, the user wants to see the sample covariance matrix of the variables in their model for diagnostic purposes. However, their data may contain many more columns than the variables used in the model.
Usage
lavInspectSampleCov(model, data, ...)
inspectSampleCov(model, data, ...)
Arguments
model |
The model that will be fit by lavaan. |
data |
The data frame being used to fit the model. |
... |
Other arguments to |
Details
One must supply both a model, coded with proper model.syntax, and
a data frame from which a covariance matrix will be calculated. This function
essentially calls sem without fitting the model, and then uses
lavInspect to obtain the sample covariance matrix and the
meanstructure.
See also
Author(s)
Jarrett Byrnes
Inspect or extract information from a lavaanList object
Description
The lavListInspect() and lavListTech() functions can be used to
inspect/extract information that is stored inside (or can be computed from) a
lavaanList object.
Usage
lavListInspect(object, what = "free", add_labels = TRUE,
add_class = TRUE, list_by_group = TRUE,
drop_list_single_group = TRUE, ...)
lavListTech(object, what = "free", add_labels = FALSE,
add_class = FALSE, list_by_group = FALSE,
drop_list_single_group = FALSE, ...)
Arguments
object |
An object of class |
what |
Character. What needs to be inspected/extracted? See Details for a
full list. Note: the |
add_labels |
If |
add_class |
If |
list_by_group |
Logical. Only used when the output are model matrices.
If |
drop_list_single_group |
If |
... |
To support old argument names. |
Details
The lavListInspect() and lavListTech() functions only differ in
the way they return the results. The lavListInspect() function will
prettify the output by default, while the lavListTech() will not attempt
to prettify the output by default.
Below is a list of possible values for the what argument, organized
in several sections:
Model matrices:
"free":A list of model matrices. The non-zero integers represent the free parameters. The numbers themselves correspond to the position of the free parameter in the parameter vector. This determines the order of the model parameters in the output of, for example,
coef()andvcov()."partable":A list of model matrices. The non-zero integers represent both the fixed parameters (for example, factor loadings fixed at 1.0) and the free parameters (ignoring any equality constraints). They correspond to all entries (fixed or free) in the parameter table. See
parTable."start":A list of model matrices. The values represent the starting values for all model parameters. Alias:
"starting_values".
Information about the data (including missing patterns):
"group":A character string. The group variable in the data.frame (if any).
"ngroups":Integer. The number of groups.
"group_label":A character vector. The group labels.
"level_label":A character vector. The level labels.
"cluster":A character vector. The cluster variable(s) in the data.frame (if any).
"nlevels":Integer. The number of levels.
"ordered":A character vector. The ordered variables.
"nobs":Integer vector. The number of observations in each group that were used in the analysis (in each dataset).
"norig":Integer vector. The original number of observations in each group (in each dataset).
"ntotal":Integer. The total number of observations that were used in the analysis. If there is just a single group, this is the same as the
"nobs"option; if there are multiple groups, this is the sum of the"nobs"numbers for each group (in each dataset).
Model features:
"meanstructure":Logical.
TRUEif a meanstructure was included in the model."categorical":Logical.
TRUEif categorical endogenous variables were part of the model."fixed_x":Logical.
TRUEif the exogenous x-covariates are treated as fixed."parameterization":Character. Either
"delta"(the Delta parameterization) or"theta"(the Theta parameterization); the stored value is in lower case.
"list":The parameter table. The same output as given by
parTable()."options":List. The option list.
"call":List. The call as returned by match.call, coerced to a list.
See Also
Examples
# fit model
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
# a data generating function
generateData <- function() lavSimulateData(HS.model, sample_nobs = 100)
set.seed(1234)
fit <- semList(HS.model, dataFunction = generateData, ndat = 5,
store_slots = "partable")
# extract information
lavListInspect(fit, "free")
lavListTech(fit, "free")
lavaan matrix representation
Description
Extend the parameter table with a matrix representation.
Usage
lavMatrixRepresentation(partable, representation = "LISREL",
allow_composites = TRUE,
add_attributes = FALSE, as_data_frame = TRUE, ...)
Arguments
partable |
A lavaan parameter table (as extracted by the
|
representation |
Character. The matrix representation style. Currently, only the all-y version of the LISREL representation is supported. |
allow_composites |
Logical. If |
add_attributes |
Logical. If |
as_data_frame |
Logical. If |
... |
Used only to support old argument names. |
Value
A list or a data.frame containing the original parameter table, plus
three columns: a "mat" column containing matrix names, and
a "row" and "col" column for the row and column indices
of the model parameters in the model matrices.
See Also
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
# extract partable
partable <- parTable(fit)
# add matrix representation (and show only a few columns)
lavMatrixRepresentation(partable)[,c("lhs","op","rhs","mat","row","col")]
lavaan Names
Description
Extract variable names from a fitted lavaan object.
Usage
lavNames(object, type = "ov", ...)
Arguments
object |
An object of class |
type |
Character. The type of variables whose names should be extracted.
See details for a complete list. Dots and underscores are interchangeable
( |
... |
Additional selection criteria. For example, |
Details
The order of the variable names, as returned by lav_object_vnames,
determines the order in which the variables are listed in the parameter
table, and therefore also in the summary output.
The following variable types are available:
-
"ov": observed variables -
"ov_x": (pure) exogenous observed variables (no mediators) -
"ov_nox": non-exogenous observed variables -
"ov_model": modeled observed variables (joint vs conditional) -
"ov_y": (pure) endogenous variables (dependent only) (no mediators) -
"ov_num": numeric observed variables -
"ov_ord": ordinal observed variables -
"ov_ind": observed indicators of latent variables -
"ov_orphan": isolated observed variables (only their intercepts or variances appear in the model syntax) -
"ov_interaction": interaction terms (defined by the colon operator) -
"th": threshold names (ordinal variables only) -
"th_mean": threshold names (ordinal and numeric variables, if any) -
"lv": latent variables -
"lv_regular": measured latent variables (defined by =~ only) -
"lv_composite": composites (defined by <~ only) -
"lv_x": (pure) exogenous variables -
"lv_y": (pure) endogenous variables -
"lv_nox": non-exogenous latent variables -
"lv_nonnormal": latent variables with non-normal indicators -
"lv_interaction": interaction terms at the latent level -
"eqs_y": variables that appear as dependent variables in a regression formula (but not indicators of latent variables) -
"eqs_x": variables that appear as independent variables in a regression formula
See Also
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
lavNames(fit, "ov")
lavaan Options
Description
Show the default options used by the lavaan() function. The
options can be changed by passing 'name = value' arguments to the
lavaan() function call, where they are added to the '...'
argument.
Option names are documented in snake_case (for example
std_lv). Dots and underscores are interchangeable when an option
is specified: the dotted spelling (std.lv), which was the only
documented spelling in lavaan versions before 0.7, remains fully
supported. The dotted spelling is the one stored in the Options
slot of a fitted object and returned by lavOptions() and
lavInspect(fit, "options").
Usage
lavOptions(x = NULL, default = NULL, mimic = "lavaan")
Arguments
x |
Character. A character string holding an option name, or a character string vector holding multiple option names. All option names are converted to lower case, and underscores are converted to dots. |
default |
If a single option is specified but not available, this value is returned. |
mimic |
Not used for now. |
Details
This is the full list of options that are accepted by the lavaan()
function, organized in several sections:
Model features:
meanstructure:If
TRUE, the means of the observed variables enter the model. If"default", the value is set based on the user-specified model, and/or the values of other arguments.int_ov_free:If
FALSE, the intercepts of the observed variables are fixed to zero.int_lv_free:If
FALSE, the intercepts of the latent variables are fixed to zero.conditional_x:If
TRUE, we set up the model conditional on the exogenous ‘x’ covariates; the model-implied sample statistics only include the non-x variables. IfFALSE, the exogenous ‘x’ variables are modeled jointly with the other variables, and the model-implied statistics reflect both sets of variables. If"default", the value is set depending on the estimator, and whether or not the model involves categorical endogenous variables. An exogenous covariate that is declared as ordered is treated as a numeric variable ifconditional_x = TRUE(with a warning). Ifconditional_x = FALSE(andfixed_x = FALSE), it is treated as an ordered variable, just like the other ordered variables in the model: it gets thresholds (and a scaling factor), and the regression coefficient of the covariate refers to its underlying latent response variable. The combinationconditional_x = FALSEandfixed_x = TRUEis not supported for an ordered covariate.fixed_x:If
TRUE, the exogenous ‘x’ covariates are considered fixed variables and the means, variances and covariances of these variables are fixed to their sample values. IfFALSE, they are considered random, and the means, variances and covariances are free parameters. If"default", the value is set depending on the mimic option.orthogonal:If
TRUE, all covariances among latent variables are set to zero.orthogonal_y:If
TRUE, all covariances among endogenous latent variables only are set to zero.orthogonal_x:If
TRUE, all covariances among exogenous latent variables only are set to zero.std_lv:If
TRUE, the metric of each latent variable is determined by fixing their (residual) variances to 1.0. IfFALSE, the metric of each latent variable is determined by fixing the factor loading of the first indicator to 1.0. If there are multiple groups,std_lv = TRUEand"loadings"is included in thegroup_equalargument, then only the latent variances of the first group will be fixed to 1.0, while the latent variances of other groups are set free.std_ov_interaction:Character. How product terms with an observed component (an observed product term such as
x1:x2, or a mixed product term such asf1:x1) are treated in the standardized solution (seestandardizedSolution). If"component"(the default), the product term is treated like a latent product term: it is scaled by the product of the standard deviations of its components, the main effects of the components are reported as simple slopes evaluated at the means of the other components, and the (co)variances and means involving the product term are centered first. If"product"(the behavior of lavaan versions before 0.7-3), the product term is treated as a variable in its own right: it is scaled by its own standard deviation, and the main effects of its components are not adjusted. Observed variables that are not standardized (for example, the exogenous covariates understd.nox) keep their metric and are not centered. Product terms with only latent components always use the component-based treatment.effect_coding:Can be logical or character string. If logical and
TRUE, this implieseffect_coding = c("loadings", "intercepts"). If logical andFALSE, it is set equal to the empty string. If"loadings"is included, equality constraints are used so that the average of the factor loadings (per latent variable) equals 1. Note that this should not be used together withstd_lv = TRUE. If"intercepts"is included, equality constraints are used so that the sum of the intercepts (belonging to the indicators of a single latent variable) equals zero. As a result, the latent mean is freely estimated and usually equals the average of the means of the involved indicators.ceq_simple:Logical. If
TRUE, and no other general (equality or inequality) constraints are used in the model, simple equality constraints are represented in the parameter table as duplicated free parameters (instead of extra rows withop = "=="). The default isFALSE.parameterization:Currently only used if data is categorical. If
"Delta"(the default), the Delta parameterization is used. If"Theta", the Theta parameterization is used. (The value is case-insensitive.)correlation:Only used for (single-level) continuous data. If
TRUE, analyze a correlation matrix (instead of a (co)variance matrix). This implies that the residual observed variances are no longer free parameters. Instead, they are set to values that ensure the model-implied variances are unity. This also affects the standard errors. Since 0.7-2, the default estimator is ML (before: GLS): the model is fit as the covariance structure\Sigma = \Delta P(\theta) \Deltawith free scale parameters\Delta(the~*~rows in the output) and unit-diagonalP(\theta), by ordinary maximum likelihood in the full moment space. Because this augmented model is exactly scale-equivariant, the correlation-metric estimates, standard errors and test statistic are identical whether the input is raw data, a covariance matrix, or a correlation matrix. The other ML-family estimators ("MLM","MLR", ...) work the same way (raw data needed). A meanstructure is supported: the mean parameters (intercepts, latent means) live in the standardized metric, mirroring the covariance side – the implied mean is\mu = \Delta (\nu + \Lambda (I - B)^{-1} \alpha), so a saturated intercept equals the standardized sample mean (mean/sd), and the model-implied means (seelavInspect(fit, "implied")) reproduce the raw sample means. The (saturated) mean structure does not affect the correlation structure.missing = "ml"(FIML) is supported as well: the pattern-based likelihood simply consumes the augmented moments, so correlation structures can be fit to incomplete data by full-information maximum likelihood (useestimator = "MLR"for sandwich standard errors under MAR); this requiresconditional_x = FALSE.conditional_x = TRUEis supported on the ML route as well: the exogenous x are standardized internally (a fixed transformation – the analysis conditions on x), the y-side scales are free~*~parameters, and the unit-variance constraint applies to the marginal variances; the result is identical (same conditional likelihood) to the jointfixed_x = TRUEanalysis. Composite models (the<~operator) are supported as well (since 0.7-2, on both the ML and the GLS route): the composite-indicator covariances are fixed in the correlation metric, and the indicator variances are absorbed by the~*~scales. The ML route requires single-level data (andmissing = "ml"requiresconditional_x = FALSE); in all other settings, a defaulted estimator quietly falls back to GLS. Estimator WLS (= ADF weights in the correlation metric) covers the non-normal case. Bothfixed_x = FALSEandfixed_x = TRUEare supported (the latter affects the way the standard errors are computed), and (since 0.7-2) alsoconditional_x = TRUE: the exogenous covariates are then standardized along with the outcomes, the inputsample_cov(if used) must be the joint (correlation or covariance) matrix including the x-variables (it is standardized internally), and the unit-variance constraint applies to the marginal (not the residual) variances of the outcomes. Alternatively,correlationmay be a character vector of (observed) variable names (for examplecorrelation = c("x1", "x2", "x3")). In that case only the listed variables are standardized to unit variance (their residual variances are fixed accordingly), while all remaining observed variables keep their original metric (a 'partial' correlation structure). This also works withconditional_x = TRUE: the listed exogenous variables are standardized along with the listed outcomes, and non-listed outcomes keep a free (residual) variance. If the model contains observed product (interaction) terms (for examplex1:y1) andcorrelation = TRUE, the product terms are automatically excluded from the correlation set: the product of standardized variables does not have unit variance, so their (co)variances remain free parameters. Note that product terms are typically highly non-normal, so the normal-theory (GLS) standard errors for their (co)variances may be too small; considerse = "robust.sem". Some combinations are not supported (yet) and fail with an error: the two-stage missing data approach (missing = "two.stage"or"robust.two.stage"), the estimators with their own moment machinery ("IV","JS","MGM","DLS","NTRLS", ...), models that mix ordered and continuous (endogenous) variables, andsam(). For models where all endogenous variables are declaredordered, the fitted moments are already correlations, andcorrelation = TRUEis redundant (but harmless). Ifcorrelationis not specified and the input looks like a correlation matrix (asample_covwith unit diagonal, or rawdatain which all continuous model variables were standardized to unit variance), a warning asks to setcorrelation = TRUE(correlation structure) orcorrelation = FALSE(ordinary covariance analysis) explicitly.composites_cov:Character string. Only used if the model contains composites. Controls whether the composite-indicator (co)variances (the elements of the
Tmatrix) are fixed to their sample values or estimated as free parameters. If"fixed", theTmatrix is fixed to the sample (co)variances. If"free", theTmatrix is estimated as free parameters. If"default", the value is resolved to"free"for multilevel models (which makes composites at every level identified) and"fixed"otherwise. For a single-level model, freeingTis fit-invariant (the degrees of freedom are unchanged).auto_fix_first:If
TRUE, the factor loading of the first indicator is set to 1.0 for every latent variable.bad_marker_crit:Only used if
auto_fix_first = TRUE. A single number (default 0.1). If larger than zero, lavaan checks – once the unrestricted (h1) sample statistics are available – whether the first indicator of each latent variable is a poor item, in the sense that it correlates weakly with the other indicators of the same factor (more precisely: the absolute value of its corrected item-total correlation is belowbad_marker_crit). If so (and a clearly better indicator is available), a warning is issued, because a (very) poor marker item often leads to convergence problems. The check is based on the (pooled) unrestricted (h1) covariance matrix, so it behaves consistently with or without missing data, categorical data, multiple groups, etc. Before the item-total correlations are computed, the indicators are aligned with their dominant common direction, so that reverse-coded indicators do not affect the check. The check is only performed in the clean default situation: the model was given as model syntax, and none of the loadings of the latent variable carry user modifiers (labels, start values, priors, bounds) or are referenced in user-specified constraints. Larger values make the check more aggressive; a value of 0 disables the check and silences the warning.bad_marker_switch:Logical (default
FALSE). Only used if thebad_marker_critcheck flagged the first indicator of a latent variable as a poor marker item. IfFALSE, lavaan only warns, and the model is estimated exactly as specified. IfTRUE, the loading of the best available indicator is fixed to 1.0 instead of the loading of the first indicator, in order to set the metric of that latent variable; if the model with the switched marker(s) does not converge, lavaan falls back to the original marker(s). (In lavaan 0.7-1 and 0.7-2, switching was the default behavior; it now must be requested explicitly.)auto_fix_single:If
TRUE, the residual variance (if included) of an observed indicator is set to zero if it is the only indicator of a latent variable.auto_var:If
TRUE, the (residual) variances of both observed and latent variables are set free.auto_cov_lv_x:If
TRUE, the covariances of exogenous latent variables are included in the model and set free.auto_cov_x:If
TRUE, the covariances between exogenous latent variables and observed exogenous covariates are also included in the model and set free (this impliesauto_cov_lv_x = TRUE). Ignored ifconditional_x = TRUE, as these covariances cannot be represented when the model is conditioned on the exogenous covariates.auto_cov_y:If
TRUE, the covariances of dependent variables (both observed and latent) are included in the model and set free.auto_cov_rv:If
TRUE, the covariances between the random slopes of a two-level model (therv()modifier) and the other random effects of the between level (the other random slopes, the random intercepts, and the between-level factors) are included in the model and set free. If these covariances are fixed to zero, the model is not invariant to the location of the covariates that carry the random slopes. This is the default in thesem(),cfa()andgrowth()functions, unlessmimic = "Mplus". Seemodel.syntaxfor the details.auto_th:If
TRUE, thresholds for limited dependent variables are included in the model and set free.auto_delta:If
TRUE, response scaling parameters for limited dependent variables are included in the model and set free.auto_efa:If
TRUE, the necessary constraints are imposed to make the (unrotated) exploratory factor analysis blocks identifiable: for each block, factor variances are set to 1, factor covariances are constrained to be zero, and factor loadings are constrained to follow an echelon pattern.
Data options:
std_ov:If
TRUE, observed variables are standardized before entering the analysis. By default, these are only the non-exogenous observed variables, unlessfixed_x = FALSE. Use this option with caution; it can be used to test whether (for example) nonconvergence was due to scaling issues. Note that this is still a covariance-based analysis: no constraints are imposed to ensure the model-implied (co)variance matrix has unit variances, and the standard errors still assume that the input was unstandardized. See also thecorrelationoption.rescale_data:Internal rescaling of badly scaled variables (new in 0.7-2). When the observed standard deviations are very heterogeneous or extreme (roughly: a max/min sd ratio beyond 1000, or sds outside [0.001, 1000]), the optimizer often fails or needs thousands of iterations, and the classical advice is to rescale the offending variables before the analysis. With
rescale_data = "auto"(the default), lavaan automates this advice exactly: each model variable is internally divided by a power of two close to its standard deviation (lossless in floating point), the model is fitted in the well-scaled metric, and the solution – estimates, standard errors, tests – is mapped back to the original metric through the exact reparameterization; fixed parameter values and starting values are transformed along, so the fitted model (and all output) is exactly the user's model in the original units.TRUEforces the rescaling;FALSE(or"none") disables it. The rescaling is skipped (with a warning if forced) for settings it does not support: summary-statistics input, multilevel or categorical data, composites, EFA blocks, product terms, estimator ULS, inequality constraints, and equality constraints that tie parameters with different scaling factors (e.g., equal loadings across indicators with very different variances – such constraints would not survive a change of units).missing:The default setting is
"listwise": all cases with missing values are removed listwise from the data before the analysis starts. This is only valid if the data are missing completely at random (MCAR). Therefore, it may not be the optimal choice, but it can be useful for a first run. If the estimator belongs to the ML family, another option is"ml"(alias:"fiml"or"direct"). This corresponds to the so-called full information maximum likelihood approach (fiml), where we compute the likelihood case by case, using all available data from that case. Note that if the model contains exogenous observed covariates, andfixed_x = TRUE(the default), all cases with any missing values on these covariates will be deleted first. The option"ml.x"(alias:"fiml.x"or"direct.x") is similar to"ml", but does not delete any cases with missing values for the exogenous covariates, even iffixed_x = TRUE. (Note: all lavaan versions < 0.6 used"ml.x"instead of"ml"). Since version 0.7-2,"ml"can also be combined withconditional_x = TRUE(single-level, continuous data): the likelihood of the observed non-x variables is then computed case by case, conditional on the (complete) exogenous covariates of that case. Cases with missing values on the exogenous covariates are deleted first, and"ml.x"is not available in this setting. Note that the robust (missing-data corrected) versions of RMSEA/CFI are not (yet) available whenconditional_x = TRUE. If you wish to use multiple imputation, you need to use an external package (e.g., mice) to generate imputed datasets, which can then be analyzed using thesemListfunction. The semTools package contains several functions to do this automatically. Another option (with continuous data) is to use"two.stage"or"robust.two.stage". In this approach, we first estimate the sample statistics (mean vector, variance-covariance matrix) using an EM algorithm. Then, we use these estimated sample statistics as input for a regular analysis (as if the data were complete). The standard errors and test statistics are adjusted correctly to reflect the two-step procedure. The"robust.two.stage"option produces standard errors and a test statistic that are robust against non-normality. Both options are available for the ML estimator (since version 0.7-2 also in combination withconditional_x = TRUE), and also for the (continuous-data) least-squares estimators"ULS","GLS","WLS","DWLS"and"DLS"; for the latter, lavaan automatically switches tose = "robust.sem"andtest = "satorra.bentler", using the two-stage variance-covariance matrix of the EM-based sample statistics (which also provides the"WLS"/"DWLS"weight matrix). In addition, for these least-squares estimators, requestingmissing = "ml"(or"fiml") is interpreted as a generic request to handle the missing values, and is silently treated asmissing = "two.stage". Both options can be combined with sampling weights (since version 0.7-3); because the plain two-stage standard errors do not account for the variability of the weights,missing = "two.stage"is then silently treated asmissing = "robust.two.stage". If (part of) the data is categorical, and the estimator is from the (W)LS family, the only option (besides listwise deletion) is"pairwise". In this three-step approach, missingness is only an issue in the first two steps. In the first step, we compute thresholds (for categorical variables) and means or intercepts (for continuous variables) using univariate information only. In this step, we simply ignore the missing values just like in mean(x, na.rm = TRUE). In the second step, we compute polychoric/polyserial/pearson correlations using (only) two variables at a time. Here we use pairwise deletion: we only keep those observations for which both values are observed (not missing), and this set may change from pair to pair. By default, in the categorical case we useconditional_x = TRUE. Therefore, any cases with missing values on the exogenous covariates will be deleted listwise from the data first. For continuous data,"pairwise"fits the pairwise-complete sample moments; for the (D)WLS/ULS estimators, the robust standard errors and scaled test statistics use the Gamma matrix of these pairwise-complete moments, but for the ML/GLS estimators, no robust standard errors or scaled test statistics are available when the data contain missing values (onlyse = "standard"andtest = "standard", or bootstrapping). Finally, if the estimator is"PML", the available options are"pairwise","available.cases"and"doubly.robust". See the PML tutorial on the lavaan website for more information about these approaches.sampling_weights_normalization:If
"none", the sampling weights (if provided) will not be transformed. If"total", the sampling weights are normalized by dividing by the total sum of the weights, and multiplying again by the total sample size. If"group", the sampling weights are normalized per group: by dividing by the sum of the weights (in each group), and multiplying again by the group size. The default is"group". (For a single group,"group"and"total"are identical; they only differ when there are multiple groups, in which case"group"keeps each group's relative contribution proportional to its sample size, matching the behavior of Mplus.) In a two-level model, the same option is used for the cluster sampling weights (see thesampling_weights_clusterargument): they are rescaled so that the implied weights of the level-1 units (each unit inherits the weight of its cluster) sum to the (total or group) sample size.sampling_weights_scaling:Only used in a two-level model, if (level-1) sampling weights are provided (see the
sampling_weightsargument). Determines how these weights are rescaled within each cluster. If"cluster"(the default), the weights are rescaled so that they sum to the cluster size. If"ecluster", they are rescaled so that they sum to the effective cluster size (the squared sum of the weights divided by the sum of the squared weights). If"none"(or"unscaled"), the weights are not rescaled. The sum of the (rescaled) weights of a cluster acts as the cluster size in the (pseudo) loglikelihood. These settings correspond to theWTSCALEoption of Mplus.sampling_weights_type:Only used when sampling weights are provided and the estimator relies on a weight matrix or sandwich variance: the least-squares family (GLS/WLS/DWLS/ULS/DLS, both continuous and categorical) and PML. Determines how the sampling weights enter the asymptotic variance (the Gamma /
nacovmatrix, or the PML first-order information), and hence the (robust) standard errors and the scaled test statistic. For GLS and ULS only the standard errors are affected; for WLS/DWLS/DLS the Gamma also feeds the weight matrix, so the point estimates shift as well. If"design"(the default), the weights are treated as sampling (design) weights and a design-based sandwich is used (the meat is weighted by the sum of the squared weights), matching the behavior of Mplus. If"frequency", the weights are treated as frequency (replication) counts (the meat is weighted by the sum of the weights), so that the results match a fit on the row-replicated data. Without sampling weights the two are identical.samplestats:Logical. If
FALSE, no sample statistics will be computed (and no estimation can take place). This can be useful when only a dummy lavaan object is requested, without any computations. The default isTRUE.
Data summary options:
sample_cov_rescale:If
TRUE, the sample covariance matrix provided by the user is internally rescaled by multiplying it with a factor (N-1)/N. If"default", the value is set depending on the estimator and the likelihood option: it is set toTRUEif maximum likelihood estimation is used andlikelihood="normal", andFALSEotherwise.ridge:Logical. If
TRUE, a small constant value is added to the diagonal elements of the covariance (or correlation) matrix before analysis. The value can be set using theridge_constantoption.ridge_constant:Numeric. Small constant used for ridging. The default value is 1e-05.
Multiple group options:
group_label:A character vector. The user can specify which group (or factor) levels need to be selected from the grouping variable, and in which order. If missing, all grouping levels are selected, in the order as they appear in the data.
group_equal:A vector of character strings. Only used in a multiple group analysis. Can be one or more of the following:
"loadings","composite.weights","intercepts","means","thresholds","regressions","residuals","residual.covariances","lv.variances"or"lv.covariances", specifying the pattern of equality constraints across multiple groups. As a shortcut, the single value"all"can be used to constrain all (free) parameters to be equal across groups; it is equivalent to listing all of the values above, except whenmeanstructure = FALSEwas explicitly requested: in that case, the model contains no mean-structure parameters, and"intercepts"and"means"are not included. When the model is not the same across groups (for example when thegroup:modifier is used to specify a different model per group), only parameters that are present in two or more groups are constrained to be equal; a parameter that occurs in a single group only is always left free. The constraints are symmetric and do not depend on the first group: a parameter that is shared by (say) the second and third group is constrained to be equal across those two groups, even if it does not appear in the first group.group_partial:A vector of character strings containing the labels of the parameters which should be free in all groups (thereby overriding the
group_equalargument for some specific parameters).group_w_free:Logical. If
TRUE, the group frequencies are considered to be free parameters in the model. In this case, a Poisson model is fitted to estimate the group frequencies. IfFALSE(the default), the group frequencies are fixed to their observed values.
Estimation options:
estimator:The estimator to be used. Can be one of the following:
"ML"for maximum likelihood,"GLS"for (normal theory) generalized least squares,"WLS"for weighted least squares (sometimes called ADF estimation),"ULS"for unweighted least squares,"DWLS"for diagonally weighted least squares, and"DLS"for distributionally-weighted least squares. These are the main options that affect the estimation. For two-level models, the least-squares estimators ("GLS","WLS","DWLS"and"ULS") fit the model to the within and between means and covariances of the unrestricted (h1) model; for"GLS", the weight matrix is the (normal-theory) expected information matrix of this unrestricted model (complete continuous data only). For convenience, the"ML"option can be extended as"MLM","MLMV","MLMVS","MLF", and"MLR". The estimation will still be plain"ML", but now with robust standard errors and a robust (scaled) test statistic. For"MLM","MLMV","MLMVS", classic robust standard errors are used (se="robust.sem"); for"MLF", standard errors are based on first-order derivatives (information = "first.order"); for"MLR", ‘Huber-White’ robust standard errors are used (se="robust.huber.white"). In addition,"MLM"will compute a Satorra-Bentler scaled (mean adjusted) test statistic (test="satorra.bentler"),"MLMVS"will compute a mean and variance adjusted test statistic (Satterthwaite style) (test="mean.var.adjusted"),"MLMV"will compute a mean and variance adjusted test statistic (scaled and shifted) (test="scaled.shifted"), and"MLR"will compute a test statistic which is asymptotically equivalent to the Yuan-Bentler T2-star test statistic (test="yuan.bentler.mplus"). Analogously, the estimators"WLSM"and"WLSMV"imply the"DWLS"estimator (not the"WLS"estimator) with robust standard errors and a mean or mean and variance adjusted test statistic. Estimators"ULSM"and"ULSMV"imply the"ULS"estimator with robust standard errors and a mean or mean and variance adjusted test statistic. Finally,"RBM"requests reduced-bias M-estimation (penalized maximum likelihood; continuous-outcome models for now). By default sandwich standard errors are used (se = "robust.huber.white"). The type of bias reduction is controlled by therbm_methodelement ofestimator_args(either"implicit"(default) or"explicit"), for exampleestimator = list(estimator = "RBM", rbm_method = "explicit"). The"explicit"method is much faster for models with many parameters (it requires a single ML fit plus a one-step correction), and is recommended in that case.likelihood:Only relevant for ML estimation. If
"wishart", the Wishart likelihood approach is used. In this approach, the covariance matrix has been divided by N-1, and both standard errors and test statistics are based on N-1. If"normal", the normal likelihood approach is used. Here, the covariance matrix has been divided by N, and both standard errors and test statistics are based on N. If"default", it depends on the mimic option: ifmimic="lavaan"ormimic="Mplus", normal likelihood is used; otherwise, Wishart likelihood is used.link:Not used yet. This is just a placeholder until the MML estimator is back.
information:If
"expected", the expected information matrix is used (to compute the standard errors). If"observed", the observed information matrix is used. If"first.order", the information matrix is based on the outer product of the casewise scores. See also the optionsh1_informationandobserved_informationfor further control. If"default", the value is set depending on the estimator, the missing argument, and the mimic option. If the argument is a vector with two elements, the first element is used for the computation of the standard errors, while the second element is used for the (robust) test statistic.h1_missing_method:Character. Only used for multilevel models with missing data (and
missing = "ml"). If"em"(the default since 0.7-1), the means and (co)variances of the unrestricted (h1) model are estimated using the EM algorithm, integrating over both the cluster random effects and the missing values (this mimics Mplus). If"fiml", the unrestricted model is estimated using quasi-Newton optimization (nlminb) with a cholesky parameterization of the covariance matrices (this was the default in versions < 0.7-1). See theem_h1_argsoption to control the EM algorithm.em_h1_args:List. Options related to the EM algorithm that is used to estimate the means and (co)variances of the unrestricted (h1) model. This is only relevant for multilevel models, and for single-level models with missing data (and
missing = "ml"ormissing = "two.stage"). The default values areem_h1_args = list(max_iter = "default", tol = "default", min_variance = 1e-05, warn = TRUE, non_pd_action = "stop", non_pd_tol = 1e-05, acceleration = "squarem", fused = TRUE). Themax_iterelement sets the maximum number of EM iterations; thetolelement sets the tolerance used to determine convergence. If"default", they are set to 500 and 1e-05 respectively in the single-level setting (where the EM algorithm stops when the largest absolute change in the parameter values is smaller thantol), and to 5000 and 1e-04 respectively in the multilevel setting (where the EM algorithm stops when the change in the loglikelihood is smaller thantol). Themin_varianceelement sets the minimum value a variance can take during the EM iterations (multilevel only): whenever a within-level variance drops below this value, it is fixed to this value (and the corresponding covariances are set to zero). If thewarnelement isTRUE(the default), a warning is produced if the EM algorithm reachesmax_iteriterations without converging. Thenon_pd_actionelement controls what happens if an EM estimated variance-covariance matrix is (near) singular: if any variance is (near) zero, or if the smallest eigenvalue of the matrix is smaller than thenon_pd_tolelement. This typically happens when a (within or between) variance of an observed variable approaches zero, but the full matrix may also be (near) singular. Ifnon_pd_action = "stop"(the default), estimation stops with an error message; if"warn", a warning is produced, and estimation continues; if"none", estimation continues silently. Theaccelerationelement controls whether the EM iterations are accelerated. If"squarem"(the default), the SQUAREM scheme (Varadhan & Roland, 2008) is used: every cycle takes two EM steps, extrapolates, and takes one stabilizing EM step from the extrapolated point, with a loglikelihood safeguard; this typically reduces the number of EM steps considerably (in particular when some variances approach zero), and converges to the same solution. If"qn", a quasi-Newton scheme (Zhou, Alexander & Lange, 2011; the"qn"method of the turboEM package) is used instead: a low-rank secant approximation of the EM map is used to take a quasi-Newton step towards the fixed point, again with a loglikelihood safeguard. If"none", the plain (unaccelerated) EM iterations are used. If thefusedelement isTRUE(the default), the loglikelihood is computed as a cheap byproduct of the E-step quantities (only used in the two-level setting with missing data, for the plain EM iterations); ifFALSE, a separate (stand-alone) loglikelihood evaluation is used in every iteration; both give identical results.h1_information:If
"structured"(the default), the unrestricted (h1) information part of the (expected, first.order or observed if h1 is used) information matrix is based on the structured, or model-implied statistics (model-implied covariance matrix, model-implied mean vector, etc.). If"unstructured", the unrestricted (h1) information part is based on sample-based statistics (observed covariance matrix, observed mean vector, etc.) If the argument is a vector with two elements, the first element is used for the computation of the standard errors, while the second element is used for the (robust) test statistic.observed_information:If
"hessian", the observed information matrix is based on the hessian of the objective function. If"h1", an approximation is used that is based on the observed information matrix of the unrestricted (h1) model. If the argument is a vector with two elements, the first element is used for the computation of the standard errors, while the second element is used for the (robust) test statistic.information_bread:Only used when the standard errors are based on a sandwich-type (robust) covariance matrix (
se = "robust.sem"orse = "robust.huber.white"). If set to"expected"or"observed", this type of information matrix is used for the bread (the outer matrices) of the sandwich only, while all the ingredients of the meat (the inner matrix) remain based on the (first element of the)informationoption. If"default", the (first element of the)informationoption is used for the bread as well, with two exceptions (both new in 0.7-2). First, for categorical data (single-level or two-level) estimated with DWLS or ULS andse = "robust.sem"(e.g., estimator"WLSMV"or"ULSMV"),"default"resolves to"observed": the bread is then based on the full hessian of the (D)WLS/ULS fit function, which (unlike the expected-information bread) remains consistent when the model does not fit perfectly. When the model fits well, both versions are virtually identical; the classic standard errors remain available withinformation_bread = "expected". The point estimates and all test statistics are not affected. Second, for the structural part of asammodel withse = "local","default"resolves to"observed"as well; see thestruc_argsargument insam. The summary header shows an additionalInformation breadline whenever the bread deviates from the (first element of the)informationoption.information_meat_hc:Character. Small-sample correction of the first-order (casewise) sandwich standard errors (new in 0.7-3). Only used when the standard errors are based on the crossproduct of casewise contributions:
se = "robust.huber.white"(casewise scores),se = "robust.sem"(casewise moment contributions), and these = "local"andse = "twostep.huber.white"standard errors ofsam. These sandwiches are the analogue of the"HC0"estimator of a regression model and inherit its small-sample downward bias. The possible values mirror the regression corrections:"HC0"(the default; no correction),"HC1"(the whole covariance matrix is multiplied byn/(n - p), withpthe number of free parameters – forsam, the number of free structural parameters, not counting the (co)variances of the exogenous variables),"HC2"and"HC3". For"HC2"and"HC3", the casewise influence values of the regression coefficients (including the intercept) of each regression equation are multiplied by(1 - h_{ij})^{-1/2}("HC2") or(1 - h_{ij})^{-1}("HC3"), whereh_{ij}is the leverage of caseiin the design matrix (intercept plus predictors) of equationj; observed predictors are taken from the data, latent predictors are replaced by their Bartlett factor scores (in local SAM: the step-1 factor scores, with products for latent interaction terms). For an observed-variable regression withfixed_x = TRUE, this reproduces the classical HC2/HC3 estimators (e.g.,sandwich::vcovHC()) exactly. All other parameters (factor loadings, (residual) variances, ...) keep their uncorrected (HC0) contributions; only"HC1"affects them. A parameter constrained equal across groups is adjusted with the leverage of each group's own equation; a coefficient that appears in several equations of the same group takes the leverage of the first equation. Simulation evidence (see the references in the source) suggests"HC2"for regressions on observed variables and for local SAM (with or without latent interactions) belowN = 500, and"HC3"for latent regressions in a joint SEM with small samples and heavy-tailed predictors, where it tracks the delete-one jackknife;"HC1"tends to overcorrect badly for latent variable models with many parameters. The corrections are available for single-level, independent observations only (not for clustered or multilevel data);"HC2"/"HC3"need continuous data (raw data forse = "robust.sem", which must be complete), and are not available forse = "local.nt"or with across-group equality constraints in the measurement part of asammodel. Point estimates and test statistics are not affected. The summary header shows an additionalInformation meat small-sample correctionline whenever the correction is not"HC0". For the local standard errors ofsam, the correction is not applied ("HC0"is used, and the summary says so) whenever a lambda truncation engaged in one of the measurement blocks (see thelambda1_floorandlambda2_floorlocal options insam): the local standard errors are already conservative in that regime, and the correction would only stack on top of that.se:If
"standard", conventional standard errors are computed based on inverting the (expected, observed or first.order) information matrix. If"robust.sem", conventional robust standard errors are computed. If"robust.huber.white", standard errors are computed based on the 'mlr' (aka pseudo ML, Huber-White) approach. If"robust", either"robust.sem"or"robust.huber.white"is used depending on the estimator, the mimic option, and whether the data are complete or not. For the non-iterative estimators with delta-method standard errors over the sample moments ("MGM","JS"/"JSA"),"robust"selects the ADF (distribution-free) moment covariance, which equals the infinitesimal-jackknife (sandwich) covariance of the estimator. For the"MGM"and"IV"estimators, the ADF moment covariance (and the corresponding test statistic"browne.residual.adf") is the default if sampling weights are used: the normal-theory version ignores the sampling weights. If"boot"or"bootstrap", bootstrap standard errors are computed using standard bootstrapping (unless Bollen-Stine bootstrapping is requested for the test statistic; in this case bootstrap standard errors are computed using model-based bootstrapping). If"none", no standard errors are computed.test:Character vector. See the documentation of the
lavTestfunction for a full list. Multiple names of test statistics can be provided. If"default", the value depends on the values of other arguments. Forestimator = "ML"(since 0.7-3), the default isc("standard", "browne.residual.nt.model"): in addition to the standard LRT chi-square statistic, Browne's residual-based (NT, model-based) test statistic (also known as the reweighted least-squares (RLS) statistic) is computed, as its type I error rates are much closer to the nominal level. With incomplete data (missing = "ml"; also for two-level data), the sample-based version ("browne.residual.nt") is used instead (since 0.7-4), where the covariance matrix of the sample statistics is based on the observed information of the saturated model, evaluated at the saturated estimates: with incomplete data, the model-based version is conservative and has less power. With sampling weights, the ADF version ("browne.residual.adf") is used instead; for two-level data, the NT model-based version is available since 0.7-4 (also withconditional_x = TRUE); in a few other settings where no suitable Gamma matrix is available, only the standard statistic is computed. See also thelavTestfunction to extract (alternative) test statistics from a fitted lavaan object. FMG test names such as"peba4","pols3","pall", and"all"can be requested here for supported ML-family models. The convenience value"fmg"resolves to"peba4_rls"for one-model tests.standard_test:Character. Choose the test statistic that will be used to compute fit measures (like CFI or RMSEA). The default is
"standard", but it could also be (for example)"Browne.residual.nt", or an FMG test name such as"peba4"or"fmg".scaled_test:Character. Choose the test statistic that will be scaled (if a scaled test statistic is requested). The default is
"standard", but it could also be (for example)"Browne.residual.nt".gamma_n_minus_oneLogical. If
TRUE, we divide the Gamma matrix by N-1 (instead of the default N).gamma_unbiasedLogical. If
TRUE, we compute an unbiased version for the Gamma matrix. Only available for single-level complete data and whenconditional_x = FALSEandfixed_x = FALSE(for now). Suffixless FMG test names use this option to choose between biased and unbiased Gamma.se_delta_second_orderLogical. If
FALSE(the default), the standard errors of defined parameters (introduced with the:=operator) and of standardized parameters (as returned bystandardizedSolution()orlavInspect(., "vcov.std.*")) are computed using the first-order delta method. IfTRUE, the second-order delta method is used, which adds the term\frac{1}{2}\textrm{tr}(H V H V)(whereHis the Hessian of the transformed parameter andVis the parameter covariance matrix) to the first-order variance approximation. This may improve accuracy when the transformation is a strongly non-linear function of the model parameters. Has no effect when standard errors are obtained by bootstrapping or by the Monte Carlo method.se_defCharacter. Method for computing standard errors (and confidence intervals) of defined parameters (introduced with the
:=operator). The default is"default"(or equivalently"delta"), which uses the delta method (respectingse_delta_second_order). Set to"monte.carlo"to use the Monte Carlo method of Preacher and Selig (2012). Under this method,Rdraws are taken from\textit{MVN}(\hat{\theta}, \widehat{\textit{Var}}(\hat{\theta})), the defined parameter is evaluated for each draw, and standard errors are obtained as the standard deviation of these realizations. Confidence intervals (inparameterEstimates()andstandardizedSolution()) are based on percentile bounds of the Monte Carlo distribution, and therefore can be asymmetric (just like bootstrap intervals). Has no effect whense = "bootstrap".monte_carloList of settings for the Monte Carlo method (used when
se_def = "monte.carlo"). Currently recognizes:R(integer; number of Monte Carlo draws; default 20000) andseed(integer orNULL; optional seed for reproducibility).bootstrap:Number of bootstrap draws, if bootstrapping is used. This can also be a list with elements
R(the number of bootstrap draws; default 1000) andmethod. Ifmethodis"refit"(the default), the model is refitted for every bootstrap sample. Ifmethodis"ij"or"hoij2", the bootstrap draws are approximated by the (first-order or second-order) infinitesimal jackknife, without refitting the model. For"hoij2", the elementsguard(logical; defaultTRUE) andguard_tol(default 0.25) control whether the model is still refitted for those bootstrap samples where the approximation is not accurate enough; seelavBootstrapfor details. In the fitted object, thebootstrapoption is always stored as a single integer (the number of bootstrap draws); the other elements are stored in thebootstrap_argsoption.bootstrap_args:List. The settings of the bootstrap (apart from the number of draws):
method,guardandguard_tol. They can also be provided as elements of thebootstrapoption (see above).do_fit:If
FALSE, the model is not fit, and the current starting values of the model parameters are preserved.backend:Character (or function). The estimation backend:
"lavaan"(the default), or the name of a backend registered withlavBackendRegister(for example a package that estimates models with data-defined (":~") parameters using a casewise likelihood). lavaan then prepares the model as withdo_fit = FALSE, hands the object to the backend, and imports its results (seelavImportResults). A bare functionfunction(object, args)is accepted as a shortcut for interactive use; it is registered under an anonymous name for the session. Withse = "bootstrap", every bootstrap replicate is estimated by the backend as well (ordinary nonparametric bootstrap only); likewise forlavBootstrap()on the fitted object.backend_args:List. Settings passed on to the backend (the
argsargument of its function).
Optimization options:
integration_ngh:Integer. The number of Gauss-Hermite quadrature points (per dimension) used for numerical integration. The default is 21. Numerical integration is used when
estimator = "MML", and for two-level models with random slopes for latent covariates (therv()modifier; only the latent-covariate slopes are integrated numerically, all other random effects are handled in closed form).control:A list containing control parameters passed to the external optimizer. By default, lavaan uses
"nlminb". See the manpage ofnlminbfor an overview of the control parameters. If another (external) optimizer is selected, see the manpage for that optimizer to see the possible control parameters.optim_method:Character. The optimizer that should be used. For unconstrained optimization or models with only linear equality constraints (i.e., the model syntax does not include any "==", ">" or "<" operators), the available options are
"nlminb"(the default),"BFGS","L-BFGS-B". These are all quasi-newton methods. A Gauss-Newton (Fisher scoring) method with Levenberg-Marquardt damping is also available (optim_method = "GN"); it can be used with the"ML","GLS","WLS","DWLS","ULS","DLS","NTRLS"and"catML"estimators, and is the default whenestimator = "DLS". For multilevel models, an EM algorithm is also available (optim_method = "em"); this is the default for two-level models withmissing = "ml"(as the EM algorithm is more robust in that setting; this also mimics Mplus); see theem_argsoption to control the EM algorithm. For two-level models with random slopes (therv()modifier),optim_method = "em"uses a dedicated EM algorithm. Note that for anyoptim_method = "em"fit, variances that are fixed to zero are replaced by the (small) valueem_args$zerovar_offset(as in Mplus, which uses the same 'minimum variance' device); as a result, the reported loglikelihood may differ slightly from anoptim_method = "nlminb"fit of the same model (which uses the exact zero values). For constrained optimization, the only available option is"nlminb_constr", which uses an augmented Lagrangian minimization algorithm.optim_force_converged:Logical. If
TRUE, pretend the model has converged, no matter what.optim_fix_saturated:Logical. Only used for multilevel models. If
TRUE(the default), and one or more blocks (levels) of the model are saturated (i.e., all variances/covariances and means/intercepts of the observed variables of that block are free and unconstrained), the free parameters of these blocks are (temporarily) fixed to their h1 (unrestricted model) estimates during optimization, as their estimated values are already known. This often helps convergence. After the optimization, they are treated as free parameters again (e.g., when standard errors are computed).optim_dx_tolNumeric. Tolerance used for checking if the elements of the (unscaled) gradient are all zero (in absolute value). The default value is 0.001.
optim_parscale:Character. If
"standardized", the optimizer works with rescaled parameters: each free parameter is multiplied by the factor that would transform it to its standardized metric (as if all observed variables had unit variance; a latent variable takes the scale of its marker indicator). This makes the optimization problem better conditioned when the observed variables have very different variances, and the scaling is safe to use with any type of constraint (the constraints are always imposed on the original parameters). The default is"none"; the retry strategy of the optimizer (seeoptim_attempts) uses"standardized"when the first attempt fails. Note that therescale_dataoption offers a more radical solution for badly scaled data.gn_args:List. Options related to the Gauss-Newton optimizer (
optim_method = "GN"). The default values aregn_args = list(max_iter = 200, tol_x = 1e-05, tol_g = 1e-06). Themax_iterelement sets the maximum number of Gauss-Newton iterations. Optimization stops when either the (scaled) gradient of the discrepancy function is smaller thantol_g, or the root mean square of the difference between the old and new parameter values is smaller thantol_x.bounds:Only used if
optim_method = "nlminb". If logical:FALSEimplies no bounds are imposed on the parameters. IfTRUE, this impliesbounds = "wide". If character, possible options are"none"(the default),"standard","wide","pos.var","pos.ov.var", and"pos.lv.var". Ifbounds = "pos.ov.var", the observed variances are forced to be nonnegative. Ifbounds = "pos.lv.var", the latent variances are forced to be nonnegative. Ifbounds = "pos.var", both observed and latent variances are forced to be nonnegative. Ifbounds = "standard", lower and upper bounds are computed for observed and latent variances, and factor loadings. Ifbounds = "wide", lower and upper bounds are computed for observed and latent variances, and factor loadings; but the range of the bounds is enlarged (allowing again for slightly negative variances). For multilevel models, the bounds are computed for each level separately, using the within and between variances of the unrestricted (h1) model (see theupper_factor_betweenelement of theoptim_boundsoption); automatic bounds are not available (yet) for models with random slopes.optim_bounds:List. This can be used instead of the
boundsargument to allow more control. Possible elements of the list arelower,upper,lower_factorandupper_factor. All of these accept a vector. Thelowerandupperelements indicate for which type of parameters bounds should be computed. Possible choices are"ov.var","lv.var","loadings"and"covariances". Thelower_factorandupper_factorelements should have the same length as thelowerandupperelements respectively. They indicate the factor by which the range of the bounds should be enlarged (for example, 1.1 or 1.2; the default is 1.0). Other elements aremin_reliability_markerwhich sets the lower bound for the reliability of the marker indicator (if any) of each factor (default is 0.1). Themin_var_lv_endoelement indicates the lower bound of the variance of any endogenous latent variable (default is 0.0). Finally, theupper_factor_betweenelement is only used for multilevel models: it is the factor by which the between-level variances of the unrestricted (h1) model are multiplied before they are used to compute the upper bounds of the between-level parameters (default is 1.5). This extra slack is needed because the model-implied between-level variances can be larger than those of the unrestricted model, in particular if the intraclass correlations are small or the number of clusters is small.pd_lv:Logical, or
"auto". IfTRUE, the model is estimated in such a way that the variance-covariance matrix of the latent variables is positive definite. To achieve this, the free (residual) variances and covariances of the latent variables (the elements of the Psi matrix) are replaced, during optimization only, by the elements of the Cholesky factor of this matrix. Covariances that are fixed to zero remain exactly zero. If the solution is in the interior of the admissible region, the results are identical to those of the default setting (pd_lv = FALSE). If the solution is on (or very close to) the boundary (for example, a correlation between two latent variables that is equal to one, or a latent variance that is equal to zero), a warning is given. In this case, the boundary is treated as an active (inequality) constraint: the standard errors are computed as if the model was restricted to this boundary (just like a parameter that sits on a bound), and some standard errors may be zero. The degrees of freedom are not adjusted, and the test statistic(s) may not follow a chi-square distribution. This option is currently only available if the variances of the latent variables are either free or fixed to a positive value (for example,std_lv = TRUE), if the covariances among the latent variables are either free or fixed to zero, and if these variances and covariances are not involved in equality or inequality constraints and have no user-specified bounds; in all other cases, an error is given. Automatic bounds (see theboundsoption) are ignored for these variances and covariances. In two-level models, the random slopes (see therv()modifier) are treated as latent variables, so that the variance-covariance matrix of the random effects is positive definite too. This option is available if the model is estimated by a quasi-Newton optimizer (for example,optim_method = "nlminb"), or by the EM algorithm (optim_method = "em"; the M-step is then a constrained M-step). If"auto", the option is applied wherever this is possible: a set of (correlated) latent variables that can not be handled (for example, becausegroup_equalincludes"lv.variances") is silently left alone instead of raising an error, and nothing is done if the optimizer does not support this option. Note that with"auto", two models that are compared may not have been estimated in the same way. The default isFALSE, unless the model contains random slopes (see therv()modifier): in that case, the default is"auto", except ifmimic = "Mplus".em_args:List. Options related to the EM algorithm that is used to estimate the model parameters when
optim_method = "em"(currently only available for multilevel models, with complete or missing data). The default values areem_args = list(max_iter = 10000, fx_tol = 1e-08, dx_tol = 1e-04, zerovar_offset = 1e-04, acceleration = "squarem", fused = TRUE). Themax_iterelement sets the maximum number of EM iterations. The EM algorithm stops when either the change in the loglikelihood is smaller thanfx_tol, or the largest absolute change in the parameter values is smaller thandx_tol. Thezerovar_offsetelement is used as the starting value for variances that are fixed to zero, as the EM algorithm cannot handle exact zero variances. Theaccelerationelement controls whether the EM iterations are accelerated by the SQUAREM scheme, and thefusedelement controls whether the loglikelihood is computed as a byproduct of the E-step (see theem_h1_argsoption for details on both). If thenlminb_handoffelement isTRUE(the default), the solution of the EM iterations is always refined by a quasi-Newton (nlminb) run, warm-started at the EM values, so that the final solution meets the same convergence criteria as a solution that is found by nlminb alone (the stopping rules of the EM algorithm are absolute criteria, and the EM solution may still be slightly off); the refined solution is only accepted if nlminb converges to an (at least) equally good solution; otherwise, the EM solution is retained. If, in addition, theearly_handoffelement isTRUE(the default), the EM phase stops early (using a loosened tolerance,max(fx_tol, 0.001)), as it only needs to provide a reliable warm start for nlminb; this is usually considerably faster, and gives the same solution; if nlminb fails from the early start, a safety net resumes the EM iterations with the strictfx_tol(and tries the hand-off once more), reproducing the non-early behavior. Ifverbose = TRUE, only the EM (or SQUAREM) cycles are shown; set theverboseelement toTRUEto also show the optimizer output of each (inner) M-step.
Parallelization options (currently only used for bootstrapping):
- parallel
The type of parallel operation to be used (if any). If missing, the default is
"no".- ncpus
Integer: number of processes to be used in parallel operation: typically one would set this to the number of available CPUs. By default this is 2 (following CRAN policy); you may set this to a higher value (for example, the number of cores as detected by
parallel::detectCores()minus one) if you wish to use more processes.- cl
An optional parallel or snow cluster for use if
parallel = "snow". If not supplied, a cluster on the local machine is created for the duration of thelavBootstrapcall.- iseed
An integer to set the seed. Or NULL if no reproducible results are needed. This works for both serial (non-parallel) and parallel settings. Internally,
RNGkind()is set to"L'Ecuyer-CMRG"ifparallel = "multicore". Ifparallel = "snow"(under windows),parallel::clusterSetRNGStream()is called which automatically switches to"L'Ecuyer-CMRG". Wheniseedis not NULL,.Random.seed(if it exists) in the global environment is left untouched.
Categorical estimation options:
zero_add:A numeric vector containing two values. These values affect the calculation of polychoric correlations when some frequencies in the bivariate table are zero. The first value only applies for 2x2 tables. The second value for larger tables. This value is added to the zero frequency in the bivariate table. If
"default", the value is set depending on the"mimic"option. By default, lavaan useszero_add = c(0.5, 0.0).zero_keep_margins:Logical. This argument only affects the computation of polychoric correlations for 2x2 tables with an empty cell, and where a value is added to the empty cell. If
TRUE, the other values of the frequency table are adjusted so that all margins are unaffected. If"default", the value is set depending on the"mimic"option. The default isTRUE.zero_cell_warn:Logical. Only used if some observed endogenous variables are categorical. If
TRUE, give a warning if one or more cells of a bivariate frequency table are empty.allow_empty_cell:Logical. If
TRUE, ignore situations where an ordinal variable has fewer categories than expected, or where a category is empty in a specific group. This argument is currently used by the blavaan package (which uses lavaan to set up the model). The argument is not expected to salvage a lavaan model that results in errors.
Starting values options:
start:If it is a character string, the two options are currently
"simple"and"default". In the first case, all parameter values are set to zero, except the factor loadings and (residual) variances, which are set to 0.7 and 1.0 respectively. Whenstartis"default", the factor loadings are estimated using the fabin3 estimator (tsls) per factor. The residual variances of observed variables are set to half the observed variance, and all other (residual) variances are set to 0.05. The remaining parameters (regression coefficients, covariances) are set to zero. Ifstartis a numerical vector, it should contain the starting values for all the free parameters (in the same order as the parameter table). Ifstartis a fitted object of classlavaan, the estimated values of the corresponding parameters will be extracted. If it is a parameter table, for example the output of theparameterEstimates()function, the values of theestorstartorustartcolumn (whichever is found first) will be extracted.rstarts:Integer. The number of refits that lavaan should try with random starting values. Random starting values are computed by drawing random numbers from a uniform distribution. Correlations are drawn from the interval [-0.5, +0.5] and then converted to covariances. Lower and upper bounds for (residual) variances are computed just like the standard bounds in bounded estimation. Random starting values are not computed for regression coefficients (which are always zero) and factor loadings of higher-order constructs (which are always unity). From all the runs that converged, the final solution is the one that resulted in the smallest value for the discrepancy function.
Check options:
check_start:Logical. If
TRUE, the starting values are checked for possibly inconsistent values (for example values implying correlations larger than one). If needed, a warning is given.check_sigma_pd:Character. If
"chol", a Cholesky decomposition is used to check if the model implied covariance matrix (Sigma) is positive definite. If"eigen", an eigen decomposition is used to check if Sigma is positive definite. The latter was the default until 0.6-20. From 0.6-21 onwards,"chol"became the default (as it is much faster).check_gradient:Logical. If
TRUE, and the model converged, a warning is given if the optimizer reported a (local) solution while not all elements of the (unscaled) gradient (as seen by the optimizer) are (near) zero, as they should be (the tolerance used is 0.001).check_post:Logical. If
TRUE, and the model converged, a check is performed after (post) fitting, to verify if the solution is admissible. This implies that all variances are non-negative, and that the model-implied covariance matrix of the latent variables (cov_lv), the covariance matrix of the residuals in the structural part of the model (psi, which also contains the residual (co)variances of the observed endogenous variables), and the covariance matrix of the residuals of the (numeric) observed variables (theta) are positive (semi-)definite. For the latter tests, we tolerate a tiny negative eigenvalue that is smaller than .Machine$double.eps^(3/4) (relative to the largest eigenvalue), treating it as being zero.check_vcov:Logical. If
TRUE, and the model converged, we check if the variance-covariance matrix of the free parameters is positive definite. We take into account possible equality and active inequality constraints. If needed, a warning is given.check_lv_names:Logical. If
TRUE, and latent variables are defined in the model, lavaan will stop with an error message if a latent variable name also occurs in the data (implying it is also an observed variable).
Verbosity options:
verbose:If
TRUE, show what lavaan is doing. During estimation, the function value is printed out during each iteration.warn:If
FALSE, suppress all lavaan-specific warning messages.debug:If
TRUE, debugging information is printed out.
Miscellaneous:
model_type:Set the model type: possible values are
"cfa","sem"or"growth". This may affect how starting values are computed, and may be used to alter the terminology used in the summary output, or the layout of path diagrams that are based on a fitted lavaan object.mimic:If
"Mplus", an attempt is made to mimic the Mplus program. If"EQS", an attempt is made to mimic the EQS program. If"default", the value is (currently) set to"lavaan", which is very close to"Mplus". Seemimicfor the list of options that are affected by each setting.representation:If
"LISREL"the classical LISREL matrix representation is used to represent the model (using the all-y variant). No other options are available (for now).implied:Logical. If
TRUE, compute the model-implied statistics, and store them in the implied slot.h1:Logical. If
TRUE, compute the unrestricted model and store the unrestricted summary statistics (and perhaps a loglikelihood) in the h1 slot.baseline:Logical. If
TRUE, compute a baseline model (currently always the independence model, assuming all variables are uncorrelated) and store the results in the baseline slot.baseline_conditional_x_free_slopes:Logical. If
TRUE, andconditional_x = TRUE, the (default) baseline model will allow the slope structure to be unrestricted.baseline_fixed_x_free_cov:Logical. If
TRUE(the default), and the model contains exogenous covariates (andconditional_x = FALSE), the covariances among the exogenous covariates are retained in the baseline (independence) model: they are freely estimated iffixed_x = FALSE, and fixed to their sample values iffixed_x = TRUE(which yields the same baseline chi-square statistic). IfFALSE, these covariances are constrained to zero in the baseline model, just like all other covariances, which leads to a larger baseline chi-square statistic (and hence higher values for incremental fit indices like the CFI). The variances of the exogenous covariates are always retained.fit_by_level:Logical. Only used for multilevel models. If
TRUE, fit (and store) the partially saturated models that are needed to compute level-specific fit measures: for each level, an auxiliary model is fitted where the model at that level is retained, while the model at the other level is saturated (in addition, level-specific baseline models are fitted as well). See thelevelargument offitMeasures. Set toFALSEto skip these additional model fits.store_vcovLogical. If
TRUE, andse=is not set to"none", store the full variance-covariance matrix of the model parameters in the vcov slot of the fitted lavaan object.parserCharacter. If
"new"(the default), the new parser is used to parse the model syntax. If"old", the original (pre 0.6-18) parser is used.
See Also
lavaan, mimic, estimator_iv, estimator_js
Examples
lavOptions()
lavOptions("std_lv")
lavOptions(c("std_lv", "orthogonal"))
# the dotted spelling is accepted too
lavOptions("std.lv")
Parameter Estimates
Description
Parameter estimates of a latent variable model.
Usage
lavParameterEstimates(object,
se = TRUE, zstat = TRUE, pvalue = TRUE, ci = TRUE,
standardized = FALSE,
fmi = FALSE, plabel = FALSE,
level = 0.95, boot_ci_type = "perc",
cov_std = TRUE, fmi_options = list(),
rsquare = FALSE,
remove_system_eq = TRUE, remove_eq = TRUE,
remove_ineq = TRUE, remove_def = FALSE,
remove_nonfree = FALSE, remove_step1 = TRUE,
remove_unused = FALSE,
remove_aux = TRUE, add_attributes = FALSE,
output = "data.frame", header = FALSE, ...)
parameterEstimates(object,
se = TRUE, zstat = TRUE, pvalue = TRUE, ci = TRUE,
standardized = FALSE,
fmi = FALSE, plabel = FALSE,
level = 0.95, boot_ci_type = "perc",
cov_std = TRUE, fmi_options = list(),
rsquare = FALSE,
remove_system_eq = TRUE, remove_eq = TRUE,
remove_ineq = TRUE, remove_def = FALSE,
remove_nonfree = FALSE, remove_step1 = TRUE,
remove_unused = FALSE,
remove_aux = TRUE, add_attributes = FALSE,
output = "data.frame", header = FALSE, ...)
Arguments
object |
An object of class |
se |
Logical. If |
zstat |
Logical. If |
pvalue |
Logical. If |
ci |
If |
level |
The confidence level required. |
plabel |
Logical. If |
boot_ci_type |
If bootstrapping was used, the type of interval required.
The value should be one of |
standardized |
Logical or character. If |
cov_std |
Logical. If TRUE, the (residual) observed covariances are scaled by the square root of the ‘Theta’ diagonal elements, and the (residual) latent covariances are scaled by the square root of the ‘Psi’ diagonal elements. If FALSE, the (residual) observed covariances are scaled by the square root of the diagonal elements of the observed model-implied covariance matrix (Sigma), and the (residual) latent covariances are scaled by the square root of diagonal elements of the model-implied covariance matrix of the latent variables. |
fmi |
Logical. If |
fmi_options |
List. If non-empty, arguments can be provided to alter the default options when the model is fitted with the complete(d) data; otherwise, the same options are used as the original model. |
remove_eq |
Logical. If |
remove_system_eq |
Logical. If |
remove_ineq |
Logical. If |
remove_def |
Logical. If |
remove_nonfree |
Logical. If |
remove_step1 |
Logical. Only used by |
remove_unused |
Logical. If |
remove_aux |
Logical. If |
rsquare |
Logical. If |
add_attributes |
Deprecated argument. Please use output= instead. |
output |
Character. If |
header |
Logical. Only used if |
... |
to support old argument names |
Value
A data.frame containing the estimated parameters, standard errors, and (by default) z-values, p-values, and the lower and upper values of the confidence intervals. If requested, extra columns are added with standardized versions of the parameter estimates.
If the model was fitted with se = "bootstrap" and
boot_ci_type = "bca", the empirical-influence design matrix used to
compute the acceleration constant is stored as the "design"
attribute of the returned data.frame (retrieve with
attr(x, "design")). This design matrix (the bootstrap frequencies)
needs more (successful) bootstrap draws than observations, no
sampling weights, and no clustered data. If these conditions are not met, or if the bootstrap
draws were approximated by the infinitesimal jackknife (see the
bootstrap option in lavOptions), the acceleration
constants are computed from the infinitesimal jackknife influence values
instead (the casewise scores, premultiplied by the inverse of the observed
information matrix); this is only possible for single-level models
estimated by ML using continuous data (or by DWLS or ULS, where the
influence values of the sample statistics are used), and no "design" attribute
is returned in this case. For clustered data (cluster bootstrap), the
influence values of the clusters are used. The parameter estimates in the bootstrap samples
themselves are available via lavInspect(object, "coef_boot").
References
Savalei, V. & Rhemtulla, M. (2012). On obtaining estimates of the fraction of missing information from FIML. Structural Equation Modeling: A Multidisciplinary Journal, 19(3), 477-494.
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
lavParameterEstimates(fit)
lavParameterEstimates(fit, output = "text")
Predict the values of latent variables (and their indicators)
Description
The main purpose of the lavPredict() function is to compute (or
‘predict’) individual scores for the latent variables in the model
(‘factor scores’). NOTE: the goal of this
function is NOT to predict future values of dependent variables as in the
regression framework! (For models with only continuous observed variables, the function lavPredictY() supports this.)
Usage
lavPredict(object, newdata = NULL, type = "lv", method = "EBM",
transform = FALSE, se = "none", acov = "none",
label = TRUE, fsm = FALSE, mdist = FALSE, rel = FALSE,
append_data = FALSE, assemble = FALSE,
level = 1L, optim_method = "bfgs", eta = NULL,
parallel = c("auto", "no", "multicore", "snow"),
ncpus = NULL, cl = NULL,
drop_list_single_group = TRUE,
mdist_draws = 2000L, eap_args = list(),
local_independence = FALSE, ...)
Arguments
object |
An object of class |
newdata |
An optional data.frame, containing the same variables as
the data.frame used when fitting the model in object. For multilevel
models, the cluster variable(s) must be included; the cluster structure
and (for |
type |
A character string. If |
method |
A character string. In the linear case (when the indicators are
continuous), the possible options are |
transform |
Logical. If |
se |
Character. If |
acov |
Similar to the |
label |
Logical. If TRUE, the columns in the output are labeled. |
fsm |
Logical. If TRUE, return the factor score matrix (the coefficient
matrix |
mdist |
Logical. If TRUE, the (squared)
Mahalanobis distances of the factor scores (if |
rel |
Logical. Only used if |
append_data |
Logical. Only used when |
assemble |
Logical. If TRUE, the separate groups are reassembled into a single data.frame with a group column, having the same dimensions as the original (or newdata) dataset. |
level |
Integer. Only used in a multilevel SEM.
If |
optim_method |
Character string. Only used in the categorical case.
If |
eta |
An optional matrix or list, containing latent variable values
for each observation. Used for computations when |
parallel |
Character. Only used in the categorical case, where factor
scores are computed by a per-observation numerical optimization. The options
are |
ncpus |
Integer. The number of processes to use in parallel computation. By default, this is 2 (following CRAN policy). You may set this to a higher value (for example, the number of available cores, minus two) if you wish to use more processes. |
cl |
An optional parallel or snow cluster for use when
|
drop_list_single_group |
Logical. If |
mdist_draws |
Integer. Only used if |
eap_args |
List. Settings for the numerical integration of
|
local_independence |
Logical. Only used if (some of) the indicators
are ordered categorical, and the model contains residual covariances.
If |
... |
To support old argument names. |
Details
The predict() function calls the lavPredict() function
with its default options.
If there are no latent variables in the model, type = "ov" will
simply return the values of the observed variables. Note that this function
can not be used to ‘predict’ values of dependent variables, given the
values of independent variables (in the regression sense). In other words,
the structural component is completely ignored (for now).
References
For an overview (and evaluation) of the various factor score methods, see:
Grice, J. W. (2001). Computing and evaluating factor scores. Psychological Methods, 6(4), 430-450. doi:10.1037/1082-989X.6.4.430
For the (continuous) regression and Bartlett methods, see:
Bartlett, M. S. (1937). The statistical conception of mental factors. British Journal of Psychology, 28, 97-104. doi:10.1111/j.2044-8295.1937.tb00863.x
Bentler, P. M., & Yuan, K.-H. (1997). Optimal conditionally unbiased equivariant factor score estimators. In M. Berkane (Ed.), Latent variable modeling and applications to causality (pp. 259-281). New York: Springer-Verlag. doi:10.1007/978-1-4612-1842-5_14
For the (categorical) Empirical Bayes Modal (EBM) and Maximum Likelihood (ML) methods, see:
Skrondal, A., & Rabe-Hesketh, S. (2004). Generalized latent variable modeling: Multilevel, longitudinal, and structural equation models. Boca Raton, FL: Chapman & Hall/CRC.
For the (categorical) Expected A Posteriori (EAP) method, see:
Bock, R. D., & Mislevy, R. J. (1982). Adaptive EAP estimation of ability in a microcomputer environment. Applied Psychological Measurement, 6(4), 431-444. doi:10.1177/014662168200600405
For the Mahalanobis distances with ordered categorical data
(mdist = TRUE), see:
Mansolf, M., & Reise, S. P. (2017). Case diagnostics for factor analysis of ordered categorical data with applications to person-fit measurement. Structural Equation Modeling: A Multidisciplinary Journal, 25(1), 86-100. doi:10.1080/10705511.2017.1367926
For the correlation-preserving factor scores (transform = TRUE), see:
ten Berge, J. M. F., Krijnen, W. P., Wansbeek, T., & Shapiro, A. (1999). Some new results on correlation-preserving factor scores prediction methods. Linear Algebra and its Applications, 289(1-3), 311-318. doi:10.1016/S0024-3795(97)10007-6
See Also
lavPredictY to predict y-variables given x-variables.
Examples
data(HolzingerSwineford1939)
## fit model
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data = HolzingerSwineford1939)
head(lavPredict(fit))
head(lavPredict(fit, type = "ov"))
## ---------------------------------------------
## standard errors for the factor scores (se =)
## ---------------------------------------------
## the standard errors are returned as the "se" attribute (a list, one
## (nobs x nfactor) matrix per group)
## for continuous indicators, the (naive) standard errors are the same
## for every observation
fscores <- lavPredict(fit, se = "standard")
attr(fscores, "se")[[1]]
## correlation-preserving (transformed) factor scores: their sample
## variance-covariance matrix matches the model-implied one, and their
## standard errors are those of the transformed scores
fscores <- lavPredict(fit, transform = TRUE, se = "standard")
attr(fscores, "se")[[1]]
## for categorical indicators, the factor scores are obtained by numerical
## optimization, and their standard errors differ from one response pattern
## (observation) to the next
## (a two-factor model is used here, as the numerical optimization and the
## Monte Carlo integration below both get expensive as the number of
## ordered indicators grows)
HS.model.ord <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6 '
HS.ord <- HolzingerSwineford1939
HS.ord[ , paste0("x", 1:6)] <-
lapply(HS.ord[ , paste0("x", 1:6)], function(x) ordered(cut(x, 3)))
fit.ord <- cfa(HS.model.ord, data = HS.ord, ordered = paste0("x", 1:6))
fscores <- lavPredict(fit.ord, se = "standard")
head(attr(fscores, "se")[[1]])
## -------------------------------------------------
## casewise Mahalanobis distances (case diagnostics)
## -------------------------------------------------
## continuous data: the squared distances are exact
fscores <- lavPredict(fit, mdist = TRUE)
head(attr(fscores, "mdist")[[1]])
## ordered categorical data: expected (squared) distances of the latent
## responses, obtained by Monte Carlo integration (Mansolf & Reise, 2017);
## set the seed for reproducibility
set.seed(123)
resid.ord <- lavPredict(fit.ord, type = "resid", mdist = TRUE)
## expected casewise residuals of the latent responses:
head(resid.ord)
## expected squared residual-based distances (person fit):
head(attr(resid.ord, "mdist")[[1]])
## ------------------------------------------
## merge factor scores to original data.frame
## ------------------------------------------
idx <- lavInspect(fit, "case.idx")
fscores <- lavPredict(fit)
## loop over factors
for (fs in colnames(fscores)) {
HolzingerSwineford1939[idx, fs] <- fscores[ , fs]
}
head(HolzingerSwineford1939)
## multigroup models return a list of factor scores (one per group)
data(HolzingerSwineford1939)
mgfit <- update(fit, group = "school", group_equal = c("loadings","intercepts"))
idx <- lavInspect(mgfit, "case.idx") # list: 1 vector per group
fscores <- lavPredict(mgfit) # list: 1 matrix per group
## loop over groups and factors
for (g in seq_along(fscores)) {
for (fs in colnames(fscores[[g]])) {
HolzingerSwineford1939[ idx[[g]], fs] <- fscores[[g]][ , fs]
}
}
head(HolzingerSwineford1939)
## -------------------------------------
## Use factor scores in subsequent models
## -------------------------------------
## see Examples in semTools package: ?plausibleValues
Predict the values of y-variables given the values of x-variables
Description
This function can be used to predict the values of (observed) y-variables given the values of (observed) x-variables in a structural equation model.
Usage
lavPredictY(object, newdata = NULL,
ynames = lav_object_vnames(object, "ov.y"),
xnames = lav_object_vnames(object, "ov.x"),
method = "conditional.mean",
label = TRUE, assemble = TRUE,
force_zero_mean = FALSE,
lambda = 0,
...)
Arguments
object |
An object of class |
newdata |
An optional data.frame, containing the same variables as
the data.frame that was used when fitting the model in |
ynames |
The names of the observed variables that should be treated as the y-variables. It is for these variables that the function will predict the (model-based) values for each observation. Can also be a list to allow for a separate set of variable names per group (or block). |
xnames |
The names of the observed variables that should be treated as the x-variables. Can also be a list to allow for a separate set of variable names per group (or block). |
method |
A character string. The only available option for now is
|
label |
Logical. If TRUE, the columns of the output are labeled. |
assemble |
Logical. If TRUE, the predictions for the separate groups in the output are reassembled into a single data.frame with a group column, having the same dimensions as the original (or newdata) dataset. |
force_zero_mean |
Logical. Only relevant if there is no mean structure.
If |
lambda |
Numeric. A lambda regularization penalty term. |
... |
To support old argument name 'force.zero.mean' |
Details
This function can be used for (SEM-based) out-of-sample predictions of
outcome (y) variables, given the values of predictor (x) variables. This
is in contrast to the lavPredict() function which (historically)
only ‘predicts’ the (factor) scores for latent variables, ignoring the
structural part of the model.
When method = "conditional.mean", predictions (for y given x)
are based on the (joint y and x) model-implied variance-covariance (Sigma)
matrix and mean vector (Mu), and the standard expression for the
conditional mean of a multivariate normal distribution. Note that if the
model is saturated (and hence df = 0), the SEM-based predictions are identical
to ordinary least squares predictions.
Lambda is a regularization penalty term to improve prediction accuracy that can
be determined using the lavPredictY_cv function.
References
de Rooij, M., Karch, J.D., Fokkema, M., Bakk, Z., Pratiwi, B.C, and Kelderman, H. (2022) SEM-Based Out-of-Sample Predictions, Structural Equation Modeling: A Multidisciplinary Journal. doi:10.1080/10705511.2022.2061494
Molina, M. D., Molina, L., & Zappaterra, M. W. (2024). Aspects of Higher Consciousness: A Psychometric Validation and Analysis of a New Model of Mystical Experience. doi:10.31219/osf.io/cgb6e
See Also
lavPredict to compute scores for latent variables.
lavPredictY_cv to determine an optimal lambda to increase
prediction accuracy.
lavResidualsY to compute the residuals for the y-variables
(observed minus predicted).
Examples
model <- '
# latent variable definitions
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + a*y2 + b*y3 + c*y4
dem65 =~ y5 + a*y6 + b*y7 + c*y8
# regressions
dem60 ~ ind60
dem65 ~ ind60 + dem60
# residual correlations
y1 ~~ y5
y2 ~~ y4 + y6
y3 ~~ y7
y4 ~~ y8
y6 ~~ y8
'
fit <- sem(model, data = PoliticalDemocracy)
lavPredictY(fit, ynames = c("y5", "y6", "y7", "y8"),
xnames = c("x1", "x2", "x3", "y1", "y2", "y3", "y4"))
Determine an optimal lambda penalty value through cross-validation
Description
This function can be used to determine an optimal lambda value for the
lavPredictY function, based on cross-validation.
Usage
lavPredictY_cv(object, data = NULL,
xnames = lav_object_vnames(object, "ov.x"),
ynames = lav_object_vnames(object, "ov.y"),
n_folds = 10L,
lambda_seq = seq(0, 1, 0.1),
...)
Arguments
object |
An object of class |
data |
A data.frame, containing the same variables as the data.frame that
was used when fitting the model in |
xnames |
The names of the observed variables that should be treated as the x-variables. Can also be a list to allow for a separate set of variable names per group (or block). |
ynames |
The names of the observed variables that should be treated as the y-variables. It is for these variables that the function will predict the (model-based) values for each observation. Can also be a list to allow for a separate set of variable names per group (or block). |
n_folds |
Integer. The number of folds to be used during cross-validation. |
lambda_seq |
An R |
... |
To support old argument names. |
Details
This function determines an optimal lambda value for use with
lavPredictY, in order to improve prediction accuracy.
References
de Rooij, M., Karch, J.D., Fokkema, M., Bakk, Z., Pratiwi, B.C, and Kelderman, H. (2022) SEM-Based Out-of-Sample Predictions, Structural Equation Modeling: A Multidisciplinary Journal. doi:10.1080/10705511.2022.2061494
Molina, M. D., Molina, L., & Zappaterra, M. W. (2024). Aspects of Higher Consciousness: A Psychometric Validation and Analysis of a New Model of Mystical Experience. doi:10.31219/osf.io/cgb6e
See Also
lavPredictY to predict the values of (observed) y-variables given
the values of (observed) x-variables in a structural equation model.
Examples
## Not run:
colnames(PoliticalDemocracy) <- c("z1", "z2", "z3", "z4",
"y1", "y2", "y3", "y4",
"x1", "x2", "x3")
model <- '
# latent variable definitions
ind60 =~ x1 + x2 + x3
dem60 =~ z1 + z2 + z3 + z4
dem65 =~ y1 + y2 + y3 + y4
# regressions
dem60 ~ ind60
dem65 ~ ind60 + dem60
# residual correlations
z1 ~~ y1
z2 ~~ z4 + y2
z3 ~~ y3
z4 ~~ y4
y2 ~~ y4
'
fit <- sem(model, data = PoliticalDemocracy, meanstructure = TRUE)
percent <- 0.5
nobs <- lavInspect(fit, "ntotal")
idx <- sort(sample(x = nobs, size = floor(percent*nobs)))
xnames = c("z1", "z2", "z3", "z4", "x1", "x2", "x3")
ynames = c("y1", "y2", "y3", "y4")
reg.results <- lavPredictY_cv(
fit,
PoliticalDemocracy[-idx, ],
xnames = xnames,
ynames = ynames,
n_folds = 10L,
lambda_seq = seq(from = .6, to = 2.5, by = .1)
)
lam <- reg.results$lambda.min
lavPredictY(fit, newdata = PoliticalDemocracy[idx,],
ynames = ynames,
xnames = xnames,
lambda = lam)
## End(Not run)
Residuals
Description
‘lavResiduals’ provides model residuals and standardized residuals from a fitted lavaan object, as well as various summaries of these residuals.
The ‘residuals()’ (and ‘resid()’) methods are just shortcuts to this function with a limited set of arguments.
Usage
lavResiduals(object, type = "cor_bentler", h1 = NULL,
se = FALSE, zstat = TRUE, summary = TRUE, elementwise = TRUE,
combine = FALSE, usrmr_ci_level = 0.90, usrmr_close_h0 = 0.05,
h1_acov = "unstructured",
add_type = TRUE, add_labels = TRUE, add_class = TRUE,
drop_list_single_group = TRUE,
maximum_number = 0L, n_largest = 5L, output = "list", ...)
Arguments
object |
An object of class |
type |
Character. Dots and underscores are interchangeable
( |
h1 |
Optional. A user-provided saturated (unrestricted) model supplying
the observed summary statistics against which the model-implied statistics are
compared. It can be a fitted |
se |
Logical. If |
zstat |
Logical. If |
summary |
Logical. If The two versions are reported with different inferential statistics, and this asymmetry is intentional. The sample RMR/SRMR/CRMR overestimate (are positively biased for) their population values. For these (biased) statistics, we report a standard error and a test of exact fit (the null hypothesis that the population value equals zero). This test relies on the known sampling distribution of the (biased) sample statistic under exact fit (Maydeu-Olivares, 2017, Eqs. 28–30), where the bias is explicitly accounted for. For the (approximately) unbiased URMR/USRMR/UCRMR, we report a standard error, a confidence interval, and a test of close fit (the null hypothesis that the population value equals a small nonzero cutoff, e.g. 0.05). The confidence interval and the close-fit test require an (approximately) unbiased and normally distributed estimator, which is precisely why the unbiased version is used here. Conversely, no test of exact fit is reported for the unbiased estimator: because it is truncated at zero, its sampling distribution is degenerate at the exact-fit boundary, so the test of exact fit is (correctly) only based on the biased statistic. |
elementwise |
Logical. If |
combine |
Logical. Only relevant when multiple blocks are
involved (multiple groups, or multiple levels). If |
usrmr_ci_level |
Numeric. The confidence level of the confidence interval that is reported (in the summary) for the unbiased URMR/USRMR/UCRMR. The default is 0.90. |
usrmr_close_h0 |
Numeric. The value of the population URMR/USRMR/UCRMR under the null hypothesis of the test of close fit that is reported (in the summary) for the unbiased estimator. The default is 0.05. |
h1_acov |
Character. If |
add_type |
Logical. If |
add_labels |
If |
add_class |
If |
drop_list_single_group |
If |
maximum_number |
Integer. Only used if |
n_largest |
Integer. Only used if |
output |
Character. By default, |
... |
To support old argument names. |
Value
If drop_list_single_group = TRUE, a list of (residualized) summary
statistics, including type, standardized residuals, and summaries. If
drop_list_single_group = FALSE, the list of summary statistics is nested
within a list for each group.
References
Bentler, P.M. and Dijkstra, T. (1985). Efficient estimation via linearization in structural models. In Krishnaiah, P.R. (Ed.), Multivariate analysis - VI, (pp. 9–42). New York, NY: Elsevier.
Ogasawara, H. (2001). Standard errors of fit indices using residuals in structural equation modeling. Psychometrika, 66(3), 421–436. doi:10.1007/BF02294443
Maydeu-Olivares, A. (2017). Assessing the size of model misfit in structural equation models. Psychometrika, 82(3), 533–558. doi:10.1007/s11336-016-9552-7
Standardized Residuals in Mplus. Document retrieved from URL http://www.statmodel.com/download/StandardizedResiduals.pdf
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data = HolzingerSwineford1939)
lavResiduals(fit)
Compute residuals for the y-variables given the values of the x-variables
Description
This function can be used to compute the (case-wise) residuals for the
(observed) y-variables in a structural equation model, defined as the
difference between the observed values and the (model-based) predicted
values that are returned by lavPredictY.
Usage
lavResidualsY(object, newdata = NULL,
ynames = lav_object_vnames(object, "ov.y"),
xnames = lav_object_vnames(object, "ov.x"),
method = "conditional.mean",
label = TRUE, assemble = TRUE,
force_zero_mean = FALSE,
lambda = 0,
...)
Arguments
object |
An object of class |
newdata |
An optional data.frame, containing the same variables as
the data.frame that was used when fitting the model in |
ynames |
The names of the observed variables that should be treated as the y-variables. It is for these variables that the function will compute the (model-based) residuals for each observation. Can also be a list to allow for a separate set of variable names per group (or block). |
xnames |
The names of the observed variables that should be treated as the x-variables. Can also be a list to allow for a separate set of variable names per group (or block). |
method |
A character string. The only available option for now is
|
label |
Logical. If TRUE, the columns of the output are labeled. |
assemble |
Logical. If TRUE, the residuals for the separate groups in the output are reassembled into a single data.frame with a group column, having the same dimensions as the original (or newdata) dataset. |
force_zero_mean |
Logical. Only relevant if there is no mean structure.
If |
lambda |
Numeric. A lambda regularization penalty term. |
... |
To support old argument names. |
Details
The residuals are computed as observed - predicted, where the
predicted values are obtained by lavPredictY using the same
arguments. See the help page of lavPredictY for more details
about how the predictions are computed.
These residuals can be used, for example, to diagnose the (SEM-based) out-of-sample prediction of outcome (y) variables, or to check the distributional assumptions (for example, multivariate normality) for the y-variables given the x-variables.
References
de Rooij, M., Karch, J.D., Fokkema, M., Bakk, Z., Pratiwi, B.C, and Kelderman, H. (2022) SEM-Based Out-of-Sample Predictions, Structural Equation Modeling: A Multidisciplinary Journal. doi:10.1080/10705511.2022.2061494
See Also
lavPredictY to compute the (model-based) predicted values for
the y-variables given the x-variables.
Examples
model <- '
# latent variable definitions
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + a*y2 + b*y3 + c*y4
dem65 =~ y5 + a*y6 + b*y7 + c*y8
# regressions
dem60 ~ ind60
dem65 ~ ind60 + dem60
# residual correlations
y1 ~~ y5
y2 ~~ y4 + y6
y3 ~~ y7
y4 ~~ y8
y6 ~~ y8
'
fit <- sem(model, data = PoliticalDemocracy)
lavResidualsY(fit, ynames = c("y5", "y6", "y7", "y8"),
xnames = c("x1", "x2", "x3", "y1", "y2", "y3", "y4"))
Extract Empirical Estimating Functions
Description
A function for extracting the empirical estimating functions of a fitted lavaan model. This is the derivative of the objective function with respect to the parameter vector, evaluated at the observed (case-wise) data. In other words, this function returns the case-wise scores, evaluated at the fitted model parameters.
Usage
estfun.lavaan(object, scaling = FALSE, ignore_constraints = FALSE,
remove_duplicated = TRUE, remove_empty_cases = TRUE, ...)
lavScores(object, scaling = FALSE, ignore_constraints = FALSE,
remove_duplicated = TRUE, remove_empty_cases = TRUE, ...)
Arguments
object |
An object of class |
scaling |
Only used for the ML estimator. If |
ignore_constraints |
Logical. If |
remove_duplicated |
If |
remove_empty_cases |
If |
... |
To accept old argument names with dots. No other arguments are accepted. |
Details
Casewise scores are available for the ML, GLS, ULS and WLS estimators, and
(since 0.7-1) for the PML (pairwise maximum likelihood) estimator. For PML,
the scores are the casewise derivatives of the pairwise log-likelihood
(including the weighted univariate part when
missing = "available.cases"); missing = "doubly.robust" is not
supported (yet). Exogenous covariates (conditional_x = TRUE) are
supported for PML only.
For two-level models (estimator ML, with complete or missing data), the
loglikelihood is a sum over the clusters, and the scores are cluster-wise
scores: the matrix has one row per cluster (in the order in which the
cluster ids first appear in the data; for multiple groups, the groups are
stacked). If cluster sampling weights are used, the score of each cluster is
multiplied by its weight. Models with conditional_x = TRUE or random
slopes are not supported (yet).
Value
A n x k matrix corresponding to n observations and k parameters. For a two-level model, the rows correspond to the clusters (see Details).
Author(s)
Ed Merkle for the ML case; the remove.duplicated,
ignore.constraints and remove.empty.cases arguments were added by
Yves Rosseel; Franz Classe for the WLS case; Yves Rosseel for the PML case.
Examples
## The famous Holzinger and Swineford (1939) example
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data = HolzingerSwineford1939)
head(lavScores(fit))
Simulation Study for a Latent Variable Model
Description
Run a (Monte Carlo) simulation study: generate many datasets from a population model, fit an analysis model to each dataset, and summarize the results (bias, standard errors, coverage, test statistics, fit measures). The ‘true’ values of the parameters of the analysis model are determined automatically.
Usage
lavSimulate(model = NULL, pop_model = NULL, sample_nobs = NULL,
data_function = lavSimulateData, data_function_args = list(),
est_true = NULL, est_true_nobs = 1e6L, ndat = 1000L, cmd = "sem",
..., fit_measures = c("cfi", "tli", "rmsea", "srmr"),
standardized = FALSE, store_slots = c("partable", "test"),
fun = NULL, show_progress = FALSE, store_failed = FALSE,
parallel = c("no", "multicore", "snow"),
ncpus = min(2L, max(1L, parallel::detectCores() - 1L, na.rm = TRUE)),
cl = NULL, iseed = NULL)
Arguments
model |
The analysis model: the model that is fitted to each dataset.
Typically, the model is described using the lavaan model syntax. See
|
pop_model |
The population model: the model that is used to generate
the data. Typically, a lavaan model syntax where the values of all the
parameters are specified (see |
sample_nobs |
The sample size of each dataset. For multiple groups, a
vector with one sample size per group. This is a shortcut for
|
data_function |
Function. The function that generates a dataset (a data
frame containing the observed variables of the analysis model). The
default is |
data_function_args |
List. Optional list of arguments that are passed
to the |
est_true |
Optional. The ‘true’ values of the parameters of the analysis
model. If |
est_true_nobs |
The (approximate) size of the single large dataset that is used to determine the ‘true’ values, if the population moments are not available (see Details). |
ndat |
Integer. The number of datasets (replications). |
cmd |
Character. The command used to fit the analysis model. The
possible choices are |
... |
Other named arguments for the function that fits the analysis
model (for example |
fit_measures |
Character vector. The fit measures that are computed for
each dataset. Use |
standardized |
If |
store_slots |
Character vector. Which slots (from a lavaan object)
should be stored for each dataset? See |
fun |
Function. An optional function which when applied to the
|
show_progress |
If |
store_failed |
Logical. If |
parallel |
The type of parallel operation to be used (if any). If
missing, the default is |
ncpus |
Integer. The number of processes to be used in parallel operation: By default, this is 2 (following CRAN policy). You may set this to a higher value (for example, the number of available CPUs). |
cl |
An optional parallel or snow cluster for use if
|
iseed |
An integer to set the seed. Or NULL if no reproducible results
are needed. See |
Details
The ‘true’ values (the est_true column in the summary) are the values
of the parameters of the analysis model in the population. They are
not simply copied from the population model: the two models may use a
different parameterization (for example, the variances of the latent
variables are fixed to unity in the population model, while the analysis
model fixes the first factor loading), the analysis model may contain
equality constraints or defined parameters (the := operator), or the
analysis model may be misspecified. Unless they are all provided by the user
(the est_true argument), they are determined as follows:
If the population moments (covariance matrix, means, thresholds) are available, the analysis model is fitted (once) to these moments, and the resulting estimates are the ‘true’ values. These values are exact. If the analysis model does not hold in the population, they are the so-called pseudo-true values (which depend on the estimator), and the summary says so. The population moments are provided by the data generating function: the function is called once, and its output is inspected for an attribute
"fit"(the lavaan object of the population model, as returned bylavSimulateData(, return_fit = TRUE); this is done automatically iflavSimulateData()is the data generating function), or an attribute"pop_moments": a list with elementscov(a named covariance matrix), and optionallymean(a named vector),th(a named list, containing for each ordered variable its standardized thresholds; the rows and columns of these variables incovshould then contain the correlations of the underlying latent responses) andnobs. If there are multiple groups, each element is a list with one element per group. A custom data generating function can copy these attributes to its output (for example, after adding missing values).If the population moments are not available (a custom data generating function without these attributes), or if they can not be used (multilevel data, ordered variables that are analysed as continuous variables, ordered variables with nonnormal latent responses), the analysis model is fitted (once) to a single large simulated dataset (with about
est_true_nobsobservations). ForlavSimulateData(), the sample size is simply increased. For other data generating functions, many datasets are stacked (at mostmax(1000, ndat)datasets). These ‘true’ values are not exact, and the summary shows how large their standard errors are (relative to the standard deviations of the estimates).If this fails too, a warning is shown, and the ‘true’ values are
NA. The simulation is still carried out.
The stream of random numbers is not disturbed by these computations: the
generated datasets are the same, whether est_true is provided or not.
Datasets where the estimation did not converge, where an error occurred, or where an ordered variable has fewer response categories than in the first dataset, are not used; the summary shows how many datasets were not used, and why.
If fixed_x = TRUE (and the data are continuous, with a single group
and a single level), the exogenous covariates are kept fixed across the
datasets, in line with the (conditional) standard errors that are computed
in this setting.
Value
An object of class lavaanList, for which several
methods are available. The summary method shows:
where the ‘true’ values come from;
for each test statistic: its average and variance, and the proportion of datasets where the model is rejected at the 0.10, 0.05 and 0.01 level;
for each fit measure: its average, standard deviation, and the 5th, 50th and 95th percentile;
for each parameter: the ‘true’ value (
est_true), the average estimate (est_ave), the bias (est_bias), the relative bias (rel_bias), the root mean squared error (rmse), the standard deviation of the estimates (se_obs), the average and the median of the standard errors (se_ave,se_med) and their ratio tose_obs(se_bias,se_bias_med; these should be close to one), the average Wald statistic (wald) and the proportion of datasets where the parameter is significant (prop_sig), the average bounds of the confidence interval (ci_lower,ci_upper) and its coverage (coverage), and the Monte Carlo standard errors of the bias, ofse_biasand of the coverage (est_bias_mcse,se_bias_mcse,coverage_mcse).
The simulate_args argument of the summary method can be used
to switch off some of these summaries, or to change the level of the
confidence intervals; see lavaanList. With
print = FALSE, the summary method returns (invisibly) a list
with the tables (pe, pe_std, test,
fit_measures). The ‘true’ values are stored in the meta slot
(est_true), together with their origin (est_true_info), the
fit measures (fit_measures) and the status of each dataset
(status).
See Also
lavSimulateData, lavaanList,
class lavaanList
Examples
# the population model: all parameter values are specified
pop.model <- ' f1 =~ 0.8*y1 + 0.7*y2 + 0.6*y3
f2 =~ 0.8*y4 + 0.7*y5 + 0.6*y6
f2 ~ 0.4*f1 '
# the analysis model
model <- ' f1 =~ y1 + y2 + y3
f2 =~ y4 + y5 + y6
f2 ~ b*f1
bsq := b*b '
# (only 10 datasets, to keep the example fast; use (at least) ndat = 1000
# in a real simulation study)
set.seed(1234)
sim <- lavSimulate(model, pop_model = pop.model, sample_nobs = 200,
ndat = 10)
summary(sim)
# fewer columns
summary(sim, simulate_args = list(mcse = FALSE, se_bias_med = FALSE,
prop_sig = FALSE, rel_bias = FALSE))
# a misspecified analysis model (an omitted cross-loading), nonnormal
# data, and robust standard errors
pop.model2 <- ' f1 =~ 0.8*y1 + 0.7*y2 + 0.6*y3 + 0.3*y4
f2 =~ 0.8*y4 + 0.7*y5 + 0.6*y6
f2 ~ 0.4*f1 '
sim2 <- lavSimulate(model, pop_model = pop.model2, sample_nobs = 200,
data_function_args = list(skewness = 1, kurtosis = 3),
estimator = "MLR", ndat = 10)
out <- summary(sim2, print = FALSE)
out$est_true_info$misspecified
out$test
Simulate Data From a Lavaan Model Syntax
Description
Simulate data starting from a lavaan model syntax.
Usage
lavSimulateData(model = NULL, model_type = "sem", meanstructure = FALSE,
int_ov_free = TRUE, int_lv_free = FALSE,
marker_int_zero = FALSE, conditional_x = FALSE,
composites = TRUE, fixed_x = FALSE,
orthogonal = FALSE, std_lv = TRUE, auto_fix_first = FALSE,
auto_fix_single = FALSE, auto_var = TRUE, auto_cov_lv_x = TRUE,
auto_cov_y = TRUE, ..., sample_nobs = 500L, ov_var = NULL,
group_label = NULL, skewness = NULL,
kurtosis = NULL, cluster_idx = NULL, seed = NULL, empirical = FALSE,
mass = FALSE, ordered_center = TRUE, return_type = "data.frame",
return_fit = FALSE, debug = FALSE, standardized = FALSE)
simulateData(model = NULL, model_type = "sem", meanstructure = FALSE,
int_ov_free = TRUE, int_lv_free = FALSE,
marker_int_zero = FALSE, conditional_x = FALSE,
composites = TRUE, fixed_x = FALSE,
orthogonal = FALSE, std_lv = TRUE, auto_fix_first = FALSE,
auto_fix_single = FALSE, auto_var = TRUE, auto_cov_lv_x = TRUE,
auto_cov_y = TRUE, ..., sample_nobs = 500L, ov_var = NULL,
group_label = NULL, skewness = NULL,
kurtosis = NULL, cluster_idx = NULL, seed = NULL, empirical = FALSE,
mass = FALSE, ordered_center = TRUE, return_type = "data.frame",
return_fit = FALSE, debug = FALSE, standardized = FALSE)
lav_data_simulate_old(..., ordered_center = FALSE)
Arguments
model |
A description of the user-specified model. Typically, the model
is described using the lavaan model syntax. See
|
model_type |
Set the model type: possible values
are |
meanstructure |
If |
int_ov_free |
If |
int_lv_free |
If |
marker_int_zero |
Logical. Only relevant if the metric of each latent
variable is set by fixing the first factor loading to unity.
If |
conditional_x |
If |
composites |
If |
fixed_x |
If |
orthogonal |
If |
std_lv |
If |
auto_fix_first |
If |
auto_fix_single |
If |
auto_var |
If |
auto_cov_lv_x |
If |
auto_cov_y |
If |
... |
additional arguments passed to the |
sample_nobs |
Number of observations. If a vector, multiple datasets
are created. If |
ov_var |
The user-specified variances of the observed variables. |
group_label |
The group labels that should be used if multiple groups are created. |
skewness |
Numeric vector. The skewness values for the observed
variables. The default ( |
kurtosis |
Numeric vector. The (excess) kurtosis values for the observed
variables. The default ( |
cluster_idx |
Optional. Only used (and only available via
|
seed |
Set random seed. |
empirical |
Logical. If |
mass |
Logical. If |
ordered_center |
Logical. Only relevant for categorical data, which is
generated by the (new) multilevel-aware engine. If |
return_type |
If |
return_fit |
If |
debug |
If |
standardized |
If |
Details
Model parameters can be specified by fixed values in the lavaan model
syntax. If no fixed values are specified, the value zero will be assumed,
except for factor loadings and variances, which are set to 0.7 and 1.0
respectively. By default, multivariate normal data are generated. However, by
providing skewness and/or kurtosis values, nonnormal multivariate data can be
generated, using the Vale & Maurelli (1983) method. Skewness and kurtosis
values that are all zero are treated as if they were NULL: the data are
then generated by the (multivariate) normal route, which also supports
empirical = TRUE. Because the Vale-Maurelli method reproduces the
requested moments only approximately, combining empirical = TRUE with
nonzero skewness or kurtosis values results in an error.
There is a single data-simulation engine. Multilevel data (model syntax
containing level: blocks, or when the cluster_idx argument is
provided) are generated by an internal multilevel worker; all single-level data
(continuous and categorical, including the ov_var, skewness,
kurtosis, standardized and mass options) are generated by
the historical single-level worker, so that the continuous, single-level output
remains byte-identical to previous versions. For multilevel data, the
ov_var, skewness, kurtosis, standardized and
mass arguments are not (yet) supported and are ignored (with a warning).
lav_data_simulate_old() is a deprecated wrapper kept for backward
compatibility; it forwards to the unified engine (with ordered_center =
FALSE by default, reproducing the historical threshold cut).
Value
The generated data. Either as a data.frame
(if return_type="data.frame"),
a numeric matrix (if return_type="matrix"),
or a covariance matrix (if return_type="cov").
Examples
# specify population model
population.model <- ' f1 =~ x1 + 0.8*x2 + 1.2*x3
f2 =~ x4 + 0.5*x5 + 1.5*x6
f3 =~ x7 + 0.1*x8 + 0.9*x9
f3 ~ 0.5*f1 + 0.6*f2
'
# generate data
set.seed(1234)
myData <- lavSimulateData(population.model, sample_nobs = 100L)
# population moments
fitted(sem(population.model))
# sample moments
round(cov(myData), 3)
round(colMeans(myData), 3)
# fit model
myModel <- ' f1 =~ x1 + x2 + x3
f2 =~ x4 + x5 + x6
f3 =~ x7 + x8 + x9
f3 ~ f1 + f2 '
fit <- sem(myModel, data=myData)
summary(fit)
lavaan frequency tables
Description
Frequency tables for categorical variables and related statistics.
Usage
lavTables(object, dimension = 2L, type = "cells", categorical = NULL,
group = NULL, statistic = "default", g2_min = 3, x2_min = 3,
p_value = FALSE, output = "data.frame", pattern_as_string = TRUE, ...)
Arguments
object |
Either a |
dimension |
Integer. If 0L, display all response patterns. If 1L,
display one-dimensional (one-way) tables; if 2L, display two-dimensional
(two-way or pairwise) tables. For the latter, the information shown
per row can be changed: if |
type |
If |
categorical |
Only used if |
group |
Only used if |
statistic |
Either a character string, or a vector of character strings
requesting one or more statistics for each cell, pattern or table. Always
available are |
g2_min |
Numeric. All cells with a G2 statistic larger than this number
are considered ‘large’, as reflected in the (optional) |
x2_min |
Numeric. All cells with a X2 statistic larger than this number
are considered ‘large’, as reflected in the (optional) |
p_value |
Logical. If |
output |
If |
pattern_as_string |
Logical. Only used for response patterns (dimension = 0L). If |
... |
To support old argument names. |
Value
If output = "data.frame", the output is presented as a data.frame
where each row is either a cell, a table, or a response pattern, depending on
the "type" argument.
If output = "table" (only for two-way tables), the output is
a list of tables (if type = "cells") in which each list element
corresponds to a pairwise table, or a single table per group (if
type = "table"). In both cases, the table entries are determined by the
(single) statistic argument.
References
Joreskog, K.G. & Moustaki, I. (2001). Factor analysis of ordinal variables: A comparison of three approaches. Multivariate Behavioral Research, 36, 347-387.
See Also
Examples
HS9 <- HolzingerSwineford1939[,c("x1","x2","x3","x4","x5",
"x6","x7","x8","x9")]
HSbinary <- as.data.frame( lapply(HS9, cut, 2, labels=FALSE) )
# using the data only
lavTables(HSbinary, dim = 0L, categorical = names(HSbinary))
lavTables(HSbinary, dim = 1L, categorical = names(HSbinary), stat=c("th.un"))
lavTables(HSbinary, dim = 2L, categorical = names(HSbinary), type = "table")
# fit a model
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HSbinary, ordered=names(HSbinary))
lavTables(fit, 1L)
lavTables(fit, 2L, type="cells")
lavTables(fit, 2L, type="table", stat=c("cor.un", "G2", "cor"))
lavTables(fit, 2L, type="table", output="table", stat="X2")
Pairwise maximum likelihood fit statistics
Description
Three measures of fit for the pairwise maximum likelihood estimation method that are based on likelihood ratios (LR) are defined:
C_F, C_M, and C_P. Subscript F signifies a comparison of model-implied proportions of full response
patterns with observed sample proportions, subscript M signifies a comparison of model-implied proportions of full response
patterns with the proportions implied by the assumption of multivariate normality, and subscript P signifies
a comparison of model-implied proportions of pairs of item responses with the observed proportions of pairs of item responses.
Usage
lavTablesFitCf(object)
lavTablesFitCp(object, alpha = 0.05)
lavTablesFitCm(object)
Arguments
object |
An object of class |
alpha |
The nominal level of significance of global fit. |
Details
C_F
The C_F statistic compares the log-likelihood of the model-implied proportions (\pi_r) with the observed proportions (p_r)
of the full multivariate responses patterns:
C_F = 2N\sum_{r}p_{r}\ln[p_{r}/\hat{\pi}_{r}],
which asymptotically has a chi-square distribution with
df_F = m^k - n - 1,
where k denotes the number of items with discrete response scales, m denotes the number of response options, and n denotes
the number of parameters to be estimated. Notice that C_F results may be biased because of large numbers of empty cells in the multivariate
contingency table.
C_M
The C_M statistic is based on the C_F statistic, and compares the proportions implied by the model of interest (Model 1)
with proportions implied by the assumption of an underlying multivariate normal distribution (Model 0):
C_M = C_{F1} - C_{F0},
where C_{F0} is C_F for Model 0 and C_{F1} is C_F for Model 1. Statistic C_M has a chi-square distribution with
degrees of freedom
df_M = k(k-1)/2 + k(m-1) - n_{1},
where k denotes the number of items with discrete response scales, m denotes the number of response options, and k(k-1)/2
denotes the number of polychoric correlations, k(m-1) denotes the number of thresholds, and n_1 is the number of parameters of the
model of interest. Notice that C_M results may be biased because of large numbers of empty cells in the multivariate contingency table. However,
bias may cancel out as both Model 1 and Model 0 contain the same pattern of empty responses.
C_P
With the C_P statistic we only consider pairs of responses, and compare observed sample proportions (p) with model-implied proportions
of pairs of responses (\pi). For items i and j we obtain a pairwise likelihood ratio test statistic C_{P_{ij}}
C_{P_{ij}}=2N\sum_{c_i=1}^m \sum_{c_j=1}^m
p_{c_i,c_j}\ln[p_{c_i,c_j}/\hat{\pi}_{c_i,c_j}],
where m denotes the number of response options and N denotes sample size. The C_P statistic has an asymptotic chi-square distribution
with degrees of freedom equal to the information (m^2 -1) minus the number of parameters (2(m-1) thresholds and 1 correlation),
df_P = m^{2} - 2(m - 1) - 2.
As k denotes the number of items, there are k(k-1)/2 possible pairs of items. The C_P statistic should therefore be applied with
a Bonferroni adjusted level of significance \alpha^*, with
\alpha^*= \alpha /(k(k-1)/2)),
to keep the family-wise error rate at \alpha. The hypothesis of overall goodness-of-fit is tested at \alpha and rejected as
soon as C_P is significant at \alpha^* for at least one pair of items. Notice that with dichotomous items, m = 2,
and df_P = 0, so that the hypothesis cannot be tested.
References
Barendse, M. T., Ligtvoet, R., Timmerman, M. E., & Oort, F. J. (2016). Structural Equation Modeling of Discrete data: Model Fit after Pairwise Maximum Likelihood. Frontiers in psychology, 7, 1-8.
Joreskog, K. G., & Moustaki, I. (2001). Factor analysis of ordinal variables: A comparison of three approaches. Multivariate Behavioral Research, 36, 347-387.
See Also
Examples
# Data
HS9 <- HolzingerSwineford1939[,c("x1","x2","x3","x4","x5",
"x6","x7","x8","x9")]
HSbinary <- as.data.frame( lapply(HS9, cut, 2, labels=FALSE) )
# Single group example with one latent factor
HS.model <- ' trait =~ x1 + x2 + x3 + x4 '
fit <- cfa(HS.model, data=HSbinary[,1:4], ordered=names(HSbinary[,1:4]),
estimator="PML")
lavTablesFitCm(fit)
lavTablesFitCp(fit)
lavTablesFitCf(fit)
Test of exact fit
Description
Compute a variety of test statistics evaluating the global fit of the model.
Usage
lavTest(lavobject, test = "standard", scaled_test = "standard",
output = "list", drop_list_single = TRUE, ...)
Arguments
lavobject |
An object of class |
test |
Character vector. Multiple names of test statistics can be provided.
If |
scaled_test |
Character. Choose the test statistic
that will be scaled (if a scaled test statistic is requested).
The default is |
output |
Character. If |
drop_list_single |
Logical. Only used when |
... |
To support old argument names. |
Value
If output = "list": a nested list with test statistics, or if
only a single test statistic is requested (and
drop_list_single = TRUE), a list with details for this test
statistic. If output = "text": the text is printed, and a
nested list of test statistics (including an info attribute) is
returned.
References
Hayakawa, K. (2019). Corrected goodness-of-fit test in covariance structure analysis. Psychological Methods, 24(3), 371–389. doi:10.1037/met0000180
Himeno, T., & Yamada, T. (2014). Estimations for some functions of covariance matrix in high dimension under non-normality and its applications. Journal of Multivariate Analysis, 130, 27–44.
Srivastava, M. S. (2005). Some tests concerning the covariance matrix in high dimensional data. Journal of the Japan Statistical Society, 35(2), 251–272.
Examples
HS.model <- '
visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9
'
fit <- cfa(HS.model, data = HolzingerSwineford1939)
lavTest(fit, test = "browne.residual.adf")
lavTest(fit, test = "peba4", output = "text")
lavTest(fit, test = "pols3", scaled_test = "RLS", output = "text")
# corrected adjusted test (Hayakawa, 2018), based on the RLS statistic
lavTest(fit, test = "mean.var.adjusted.corrected", scaled_test = "RLS",
output = "text")
Invariance analysis of aligned measurement parameters
Description
Post-estimation invariance analysis of the measurement parameters of a
multiple-group model with efa blocks that were rotated with the agreement
rotation (rotation_args = list(mg_agreement = TRUE)), of a
confirmatory model aligned with alignment = "fixed" or
"free" (see alignment), or of a model with both,
following the
procedure of the alignment method (Asparouhov and Muthen, 2014). For every
aligned loading, and for every aligned intercept (or threshold, for an
ordered indicator) if the intercepts were aligned
(mg_agreement_intercepts), the groups are divided into an
(approximately) invariant set and the non-invariant groups.
Usage
lavTestAlignment(object, p_connect = 0.01, p_set = 0.001, max_iter = 100L)
Arguments
object |
An object of class |
p_connect |
Numeric. Two groups are ‘connected’ when the p-value of the pairwise test of equality of their parameter exceeds this value. The largest connected set of groups is the starting invariant set. |
p_set |
Numeric. In the iterations, a group is kept in (or added to) the invariant set when the p-value of the test of its parameter against the average over the invariant set exceeds this value, and removed otherwise. |
max_iter |
Integer. The maximum number of iterations per parameter. |
Details
For every parameter, the procedure is the following. (1) The equality of
the parameter is tested for every pair of groups with a z test, using the
(delta method) covariance matrix of the aligned estimates. Two groups are
connected when the p-value exceeds p_connect; the starting invariant
set is the largest connected set of groups. (2) The average of the parameter
over the invariant set is computed, and every group is tested against that
average. The groups with a p-value above p_set form the new invariant
set. This is repeated until the set no longer changes (or a cycle is
detected). (3) The average over the final invariant set, the non-invariant
groups, the contribution of the parameter to the agreement (loss) function
of the rotation, and an R-square are reported. The R-square is the
proportion of the across-group variance of the unaligned parameter (the
loading with a unit-variance factor, or the intercept (threshold) with a zero factor
mean) that is explained by the group differences in factor variances and
means (Asparouhov and Muthen, 2014, eqs. 13 and 14); it is only computed
with three or more groups. A value close to one means that the group
differences in the unaligned parameter are absorbed by the factor variances
and means, a value close to zero that they are not.
Value
A data.frame of class lavaan.data.frame with one row per parameter:
the parameter (lhs, op, rhs), its average over
the invariant set, the invariant set and the noninvariant
groups (group labels), the R-square (r2) and the
contribution of the parameter to the loss function. The attributes
pvalue (the p-value of every group against the average of the final
invariant set) and invariant (logical) hold the parameter by group
matrices.
References
Asparouhov, T., & Muthen, B. (2014). Multiple-group factor analysis alignment. Structural Equation Modeling, 21(4), 495–508.
See Also
alignment for the alignment of a confirmatory model;
esem for the rotation options of the agreement rotation,
including the alignment of the loadings and the intercepts of efa blocks.
Examples
HS <- HolzingerSwineford1939
model <- ' efa("b")*f1 + efa("b")*f2 + efa("b")*f3 =~
x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 '
# a (partially specified) target towards the confirmatory pattern
target <- matrix(NA, 9, 3)
target[4:9, 1] <- 0; target[c(1:3, 7:9), 2] <- 0; target[1:6, 3] <- 0
# alignment of the loadings and the intercepts
fit <- cfa(model, data = HS, group = "school", meanstructure = TRUE,
rotation = "target",
rotation_args = list(target = target, mg_agreement = TRUE,
mg_agreement_method = "loading.alignment",
mg_agreement_weight = 1, mg_agreement_scales = "free",
mg_agreement_rotate = FALSE, mg_agreement_intercepts = "fixed",
mg_agreement_group_weights = "sqrt.nobs"))
lavTestAlignment(fit)
LRT test
Description
LRT test for comparing (nested) lavaan models.
Usage
lavTestLRT(object, ..., method = "default", test = "default",
a_method = "delta", scaled_shifted = TRUE,
check_nested = TRUE,
type = "Chisq", model_names = NULL)
anova(object, ...)
Arguments
object |
An object of class |
... |
additional objects of class |
method |
Character string. The possible options are
|
test |
Character string specifying which scaled test statistics to use,
in case multiple scaled |
a_method |
Character string. The possible options are |
scaled_shifted |
Logical. Only used when method = |
check_nested |
Logical. If |
type |
Character. If |
model_names |
Character vector. If provided, use these model names in the first column of the anova table. |
Details
The anova function for lavaan objects simply calls the
lavTestLRT function, which has a few additional arguments.
For models with a casewise likelihood (data-defined, ":~",
parameters estimated by an external backend; random slopes), no
chi-square test statistic exists. When all models belong to these
classes, the models are compared by their log-likelihoods directly:
twice the difference in log-likelihood between consecutive models
(ordered by their number of free parameters) is referred to a
chi-square distribution with the difference in the number of free
parameters as degrees of freedom. The method, test and
type arguments are ignored, and such models can not be
compared with models fitted to summary statistics.
The chi-squared difference test is only valid when all models are
(nested and) fitted to the same set of sample statistics. Several
sanity checks are therefore carried out (in the spirit of
semTools::net()): the number of groups, the group labels, the
(group-specific) numbers of observations, and the observed sample
statistics must all be identical across models. If any of these
checks fails, a warning is issued (but the table is still computed).
In particular, a single-group (pooled) model cannot be compared
directly with a multiple-group model: their test statistics are
computed relative to different (saturated) models. Instead, refit the
pooled model as a multiple-group model in which all parameters are
constrained to be equal across groups (group_equal = "all"),
and compare that model with the unrestricted multiple-group model.
See the Examples section for an illustration.
The only test= options that currently have actual consequences are
"satorra.bentler", "yuan.bentler", or "yuan.bentler.mplus"
because "mean.var.adjusted" and "scaled_shifted" are
currently distinguished by the scaled_shifted argument.
See lavOptions for details about the test= options
implied by robust estimator= options. The "default" is to
select the first available scaled statistic, if any. To check which test(s)
were computed when fitting your model(s), use
lavInspect(fit, "options")$test.
If type = "Chisq" and the test statistics are scaled, a
special scaled difference test statistic is computed. If method is
"satorra.bentler.2001", a simple approximation is used
described in Satorra & Bentler (2001). In some settings,
this can lead to a negative scaling factor (and hence a negative test
statistic). In that case, a warning is issued and the unscaled
chi-squared difference test is reported instead (the "scaled"
attribute of the result is then FALSE). To ensure a positive
test statistic, we can use the method proposed by
Satorra & Bentler (2010). Alternatively, when method="satorra.2000",
the original formulas of Satorra (2000) are used. The latter is used for
model comparison when ... contains additional (nested) models.
Even when test statistics are scaled in object or ...,
users may request the method="standard" test statistic,
without a robust adjustment.
Conversely, a robust method= ("satorra.bentler.2001",
"satorra.bentler.2010" or "satorra.2000") can only be applied
when the models were fitted with a robust (scaled) test statistic. If none
of the models in object or ... were fitted with a robust test
statistic, a robust method= cannot be honored: in that case a warning
is issued, the method= argument is ignored, and a standard (regular)
chi-squared difference test is returned.
FMG nested tests are available when type = "Chisq" and
test is an FMG test name. The supported nested FMG methods are
"pall", "all", "peba" and "pols" variants.
The convenience value "fmg" resolves to "pall_ug_rls" for
single-group comparisons and "pall_ug_ml" for multiple-group
comparisons.
They use the Satorra (2000) UGamma projection; method may be left
at "default" or set to "standard" or
"satorra.2000". Other nested LRT methods are not used for FMG
tests.
Value
An object of class anova. When given a single argument, it simply returns the test statistic of this model. When given a sequence of objects, this function tests the models against one another, after reordering the models according to their degrees of freedom.
The object carries a few (hidden) attributes that record which
difference test was computed (intended for developers; new in 0.7-3):
"type" (the type of test, in canonical spelling, e.g.
"chisq" or "browne.residual.nt.model"), "method"
(the method that was used for a scaled difference test, e.g.
"satorra.bentler.2001"; "standard" for an unscaled
difference test), "test" (the name of the scaled test statistic
the difference test was based on, e.g. "satorra.bentler";
"standard" if unscaled) and "scaled" (logical). For
scaled difference tests, the attributes "scale" (and
"shift") contain the scaling factors (and shift parameters).
Note
If there is a lavaan model stored in
object@external$h1.model, it will be added to ...
References
Satorra, A. (2000). Scaled and adjusted restricted tests in multi-sample analysis of moment structures. In Heijmans, R.D.H., Pollock, D.S.G. & Satorra, A. (eds.), Innovations in multivariate statistical analysis: A Festschrift for Heinz Neudecker (pp.233-247). London, UK: Kluwer Academic Publishers.
Satorra, A., & Bentler, P. M. (2001). A scaled difference chi-square test statistic for moment structure analysis. Psychometrika, 66(4), 507-514. doi:10.1007/BF02296192
Satorra, A., & Bentler, P. M. (2010). Ensuring positiveness of the scaled difference chi-square test statistic. Psychometrika, 75(2), 243-248. doi:10.1007/s11336-009-9135-y
Foldnes, N., Moss, J., & Gronneberg, S. (2024). Improved goodness of fit procedures for structural equation models. Structural Equation Modeling: A Multidisciplinary Journal, 1-13. doi:10.1080/10705511.2024.2372028
Bentler, P. M., & Satorra, A. (2010). Testing model nesting and equivalence. Psychological Methods, 15(2), 111-123. doi:10.1037/a0019625
Asparouhov, T., & Muthen, B. (2019). Nesting and equivalence testing for structural equation models. Structural Equation Modeling: A Multidisciplinary Journal, 26(2), 302-309. doi:10.1080/10705511.2018.1513795
Foldnes, N., Gronneberg, S., & Moss, J. (2026). Penalized eigenvalue block averaging: Extension to nested model comparison and Monte Carlo evaluations. Behavior Research Methods, 58(4). doi:10.3758/s13428-026-02968-4
Examples
HS.model <- '
visual =~ x1 + b1*x2 + x3
textual =~ x4 + b2*x5 + x6
speed =~ x7 + b3*x8 + x9
'
fit1 <- cfa(HS.model, data = HolzingerSwineford1939)
fit0 <- cfa(HS.model, data = HolzingerSwineford1939,
orthogonal = TRUE)
lavTestLRT(fit1, fit0)
## A single-group (pooled) model can NOT be compared directly with a
## multiple-group model; the warning explains why the test is invalid:
HS <- '
visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9
'
fit.pooled <- cfa(HS, data = HolzingerSwineford1939, meanstructure = TRUE)
fit.groups <- cfa(HS, data = HolzingerSwineford1939, group = "school")
lavTestLRT(fit.pooled, fit.groups) # invalid comparison (warning)
## A valid alternative: refit the pooled model as a multiple-group model
## with all parameters constrained to be equal across groups
fit.pooled2 <- cfa(HS, data = HolzingerSwineford1939, group = "school",
group_equal = "all")
lavTestLRT(fit.pooled2, fit.groups) # valid comparison
## When multiple test statistics are selected when the model is fitted,
## use the type= and test= arguments to select a test for comparison.
## refit models, requesting 6 test statistics (in addition to "standard")
t6.1 <- cfa(HS.model, data = HolzingerSwineford1939,
test = c("browne.residual.adf","scaled.shifted","mean.var.adjusted",
"satorra.bentler", "yuan.bentler", "yuan.bentler.mplus"))
t6.0 <- cfa(HS.model, data = HolzingerSwineford1939, orthogonal = TRUE,
test = c("browne.residual.adf","scaled.shifted","mean.var.adjusted",
"satorra.bentler", "yuan.bentler", "yuan.bentler.mplus"))
## By default (test="default", type="Chisq"), the first scaled statistic
## requested will be used. Here, that is "scaled.shifted"
lavTestLRT(t6.1, t6.0)
## But even if "satorra.bentler" were requested first, method="satorra.2000"
## provides the scaled-shifted chi-squared difference test:
lavTestLRT(t6.1, t6.0, method = "satorra.2000")
## == lavTestLRT(update(t6.1, test = "scaled.shifted"), update(t6.0, test = "scaled.shifted"))
## The mean- and variance-adjusted (Satterthwaite) statistic implies
## scaled_shifted = FALSE
lavTestLRT(t6.1, t6.0, method = "satorra.2000", scaled_shifted = FALSE)
## Because "satorra.bentler" is not the first scaled test in the list,
## we MUST request it explicitly:
lavTestLRT(t6.1, t6.0, test = "satorra.bentler") # method="satorra.bentler.2001"
## == lavTestLRT(update(t6.1, test = "satorra.bentler"),
## update(t6.0, test = "satorra.bentler"))
## The "strictly-positive test" is necessary when the above test is < 0:
lavTestLRT(t6.1, t6.0, test = "satorra.bentler", method = "satorra.bentler.2010")
## Likewise, other scaled statistics can be selected:
lavTestLRT(t6.1, t6.0, test = "yuan.bentler")
## == lavTestLRT(update(t6.1, test = "yuan.bentler"),
## update(t6.0, test = "yuan.bentler"))
lavTestLRT(t6.1, t6.0, test = "yuan.bentler.mplus")
## == lavTestLRT(update(t6.1, test = "yuan.bentler.mplus"),
## update(t6.0, test = "yuan.bentler.mplus"))
## To request the difference between Browne's (1984) residual-based statistics,
## rather than statistics based on the fitted model's discrepancy function,
## use the type= argument:
lavTestLRT(t6.1, t6.0, type = "browne.residual.adf")
## Despite requesting multiple robust tests, it is still possible to obtain
## the standard chi-squared difference test (i.e., without a robust correction)
lavTestLRT(t6.1, t6.0, method = "standard")
## == lavTestLRT(update(t6.1, test = "standard"), update(t6.0, test = "standard"))
## FMG nested p-values use the Satorra (2000) UGamma projection
lavTestLRT(fit1, fit0, method = "satorra.2000", test = "pall")
Nesting and Equivalence Testing (NET)
Description
Checks – for every pair of fitted models – whether the more restricted model is nested within the less restricted model in the covariance sense, using the NET procedure of Bentler & Satorra (2010); for pairs of models with equal degrees of freedom, it checks whether the models are equivalent.
Usage
lavTestNET(object, ..., crit = 1e-7, npoints = 1L,
iseed = 12345L, model_names = NULL)
Arguments
object |
An object of class |
... |
additional (at least one) objects of class
|
crit |
Numeric. The criterion applied to the minimum of the fit
function when the less restricted model is fitted to the model-implied
moments of the more restricted model: values below |
npoints |
Integer. The number of parameter points of the restricted
model where the check is carried out. The first point is always the
vector of parameter estimates. If |
iseed |
Integer. The seed for the random perturbations (only used if
|
model_names |
Character vector. If provided, use these model names in the rows and columns of the result. |
Details
The procedure works as follows: the model-implied (first and) second order moments of the more restricted model are treated as if they were sample statistics, and the less restricted model is fitted to these moments. If (and only if) the minimum of the fit function is zero, the less restricted model can exactly reproduce these moments, and the more restricted model is nested within the less restricted model at this parameter point. If both models have the same degrees of freedom and each model is nested within the other, the models are equivalent.
Whenever the nesting can be established parametrically (the parameter table of the restricted model equals the parameter table of the less restricted model with some free parameters fixed and/or constrained to be equal), no refitting is needed, and the (numerically exact) verdict is based on the parameter tables alone.
Note that nesting in the covariance sense does not by itself guarantee that the usual chi-squared difference test behaves as a chi-square variate: if the nesting only holds on the boundary of the parameter space (for example, a variance fixed to zero), the standard regularity conditions fail.
The procedure is not available for multilevel models, and (currently) not
for categorical models with conditional_x = TRUE, correlation
structures, or models involving auxiliary variables.
Value
A list of class lavaan.net with elements nested (a logical
matrix; entry [i, j] indicates whether the model in row i is
nested within the model in column j; NA means the pair could
not be checked, or the result was inconclusive), fx (the
corresponding fit function minima), reason (a character matrix
explaining – for pairs that could not be checked – why the check was
skipped; these reasons are also shown by the print method), df
(the degrees of freedom of the models, in the order used in the matrix),
crit and npoints.
References
Bentler, P. M., & Satorra, A. (2010). Testing model nesting and equivalence. Psychological Methods, 15(2), 111-123. doi:10.1037/a0019625
Asparouhov, T., & Muthen, B. (2019). Nesting and equivalence testing for structural equation models. Structural Equation Modeling: A Multidisciplinary Journal, 26(2), 302-309. doi:10.1080/10705511.2018.1513795
See Also
lavTestLRT, which uses this machinery (see its
check_nested argument) to warn when a chi-squared difference test
is requested for non-nested models.
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit1 <- cfa(HS.model, data = HolzingerSwineford1939)
# nested: the same model with orthogonal factors
fit0 <- cfa(HS.model, data = HolzingerSwineford1939, orthogonal = TRUE)
# equivalent: the same model with a different scaling of the factors
fit1b <- cfa(HS.model, data = HolzingerSwineford1939, std_lv = TRUE)
# not nested
model2 <- ' f1 =~ x1 + x2 + x3 + x4
f2 =~ x5 + x6 + x7 + x8 + x9 '
fit2 <- cfa(model2, data = HolzingerSwineford1939)
lavTestNET(fit1, fit0, fit1b, fit2,
model_names = c("3f", "3f-orth", "3f-std.lv", "2f"))
Score test
Description
Score test (or Lagrange Multiplier test) for releasing one or more fixed or constrained parameters in the model.
Usage
lavTestScore(object, add = NULL, release = NULL,
univariate = TRUE, cumulative = FALSE,
epc = FALSE, standardized = epc, cov_std = epc,
verbose = FALSE, warn = TRUE, information = "expected", ...)
Arguments
object |
An object of class |
add |
Either a character string (typically between single quotes) or a parameter table containing additional (currently fixed-to-zero) parameters for which the score test must be computed. |
release |
Vector of integers. The indices of the constraints that should be released. The indices correspond to the order in which the equality constraints appear in the parameter table. |
univariate |
Logical. If |
cumulative |
Logical. If |
epc |
Logical. If |
standardized |
If |
cov_std |
Logical. See |
verbose |
Logical. Not used for now. |
warn |
Logical. If |
information |
|
... |
to allow use of old argumentname cov_std |
Details
This function can be used to compute both multivariate and univariate
score tests. There are two modes: 1) releasing fixed-to-zero parameters
(using the add argument), and 2) releasing existing equality
constraints (using the release argument). The two modes cannot
be used simultaneously.
When adding new parameters, they should not already be part of the model (i.e. not listed in the parameter table). If you want to test for a parameter that was explicitly fixed to a constant (say to zero), it is better to label the parameter, and use an explicit equality constraint.
In addition to the standard (normal-theory) score test, robust
versions are computed whenever the fitted object provides the
ingredients for a sandwich-type covariance matrix: either because
robust standard errors were requested (e.g.,
se = "robust.sem" or se = "robust.huber.white"), or
because a scaled test statistic was requested (e.g.,
test = "satorra.bentler"). Following Satorra (2000), three
robust versions are reported: a mean-scaled statistic
(score.scaled), a mean-and-variance adjusted statistic with
fractional degrees of freedom (score.adjusted), and the
generalized, asymptotically distribution-free statistic
(score.robust). For a single restriction, the three versions
coincide. The univariate (and cumulative) score tests are then
accompanied by scaled counterparts in the X2.scaled column.
Note that for estimators that are not asymptotically efficient
(e.g., DWLS, ULS and PML), only the robust
versions have the correct asymptotic distribution.
Value
A list containing at least one data.frame:
-
$test: The total score test, with columns for the score test statistic (X2), the degrees of freedom (df), and a p value under the\chi^2distribution (p.value). If robust versions could be computed, three additional rows are included:score.scaled,score.adjustedandscore.robust(see Details). -
$uni: Optional (ifunivariate=TRUE). Each 1-df score test, equivalent to modification indices. If robust versions could be computed, the scaled statistics are provided in theX2.scaledandp.value.scaledcolumns. Ifepc=TRUEwhenadding parameters (not when releasing constraints), an unstandardized EPC is provided for each added parameter, as would be returned bymodificationIndices. -
$cumulative: Optional (ifcumulative=TRUE). Cumulative score tests, with scaled counterparts if robust versions could be computed. -
$epc: Optional (ifepc=TRUE). Parameter estimates, expected parameter changes, and expected parameter values if all the tested constraints were freed.
References
Bentler, P. M., & Chou, C. P. (1993). Some new covariance structure model improvement statistics. Sage Focus Editions, 154, 235-255.
Satorra, A. (2000). Scaled and adjusted restricted tests in multi-sample analysis of moment structures. In Heijmans, R.D.H., Pollock, D.S.G. & Satorra, A. (Eds.), Innovations in multivariate statistical analysis: A festschrift for Heinz Neudecker (pp. 233-247). London: Kluwer Academic Publishers.
Examples
HS.model <- '
visual =~ x1 + b1*x2 + x3
textual =~ x4 + b2*x5 + x6
speed =~ x7 + b3*x8 + x9
b1 == b2
b2 == b3
'
fit <- cfa(HS.model, data=HolzingerSwineford1939)
# test 1: release both two equality constraints
lavTestScore(fit, cumulative = TRUE)
# test 2: the score test for adding two (currently fixed
# to zero) cross-loadings
newpar = '
visual =~ x9
textual =~ x3
'
lavTestScore(fit, add = newpar)
# equivalently, "add" can be a parameter table specifying parameters to free,
# but must include some additional information:
PT.add <- data.frame(lhs = c("visual","textual"),
op = c("=~","=~"),
rhs = c("x9","x3"),
user = 10L, # needed to identify new parameters
free = 1, # arbitrary numbers > 0
start = 0) # null-hypothesized value
PT.add
lavTestScore(fit, add = PT.add) # same result as above
Wald test
Description
Wald test for testing a linear hypothesis about the parameters of a fitted lavaan object.
Usage
lavTestWald(object, constraints = NULL, verbose = FALSE)
Arguments
object |
An object of class |
constraints |
A character string (typically between single quotes) containing one or more equality constraints. See examples for more details. |
verbose |
Logical. If |
Details
The constraints are specified using the "==" operator. Both
the left-hand side and the right-hand side of the equality can contain
a linear combination of model parameters, or a constant (like zero).
The model parameters must be specified by their user-specified labels.
Names of defined parameters (using the ":=" operator) can be
included too.
The test statistic is based on the variance-covariance matrix of the
estimated parameters (vcov) of the fitted object. Therefore, if
robust standard errors were requested for the fitted object (e.g.,
se = "robust.sem" or se = "robust.huber.white"), the main
test statistic is already the generalized (‘robust’) Wald test
described in Satorra (2000). In that case (or when a scaled test
statistic was requested, so that the ingredients for a sandwich-type
covariance matrix are available), additional versions of the Wald
test statistic are computed as well: the standard (normal-theory)
statistic (stat.standard), a mean-scaled statistic
(stat.scaled), a mean-and-variance adjusted statistic with
fractional degrees of freedom (stat.adjusted), and the
generalized statistic (stat.robust); see Satorra (2000).
Value
A list containing at least three elements: the Wald test statistic
(stat), the degrees of freedom (df), and a p-value under
the chi-square distribution (p.value). If robust versions could
be computed, the list also contains the standard, scaled, adjusted and
generalized versions of the test statistic, together with their
p-values (see Details).
References
Satorra, A. (2000). Scaled and adjusted restricted tests in multi-sample analysis of moment structures. In Heijmans, R.D.H., Pollock, D.S.G. & Satorra, A. (Eds.), Innovations in multivariate statistical analysis: A festschrift for Heinz Neudecker (pp. 233-247). London: Kluwer Academic Publishers.
Examples
HS.model <- '
visual =~ x1 + b1*x2 + x3
textual =~ x4 + b2*x5 + x6
speed =~ x7 + b3*x8 + x9
'
fit <- cfa(HS.model, data=HolzingerSwineford1939)
# test 1: test about a single parameter
# this is the 'chi-square' version of the
# z-test from the summary() output
lavTestWald(fit, constraints = "b1 == 0")
# test 2: several constraints
con = '
2*b1 == b3
b2 - b3 == 0
'
lavTestWald(fit, constraints = con)
Utility Functions: Constraints
Description
Utility functions for equality and inequality constraints.
Usage
lav_con_parse(partable = NULL, constraints = NULL, theta = NULL,
debug = FALSE, box_fast = NULL)
lav_pt_con_ceq(partable, con = NULL, debug = FALSE,
txt_only = FALSE)
lav_pt_con_ciq(partable, con = NULL, debug = FALSE,
txt_only = FALSE)
lav_pt_con_def(partable, con = NULL, debug = FALSE,
txt_only = FALSE, warn = TRUE)
Arguments
partable |
A lavaan parameter table. |
constraints |
A character string containing the constraints. |
theta |
A numeric vector. Optional vector with values for the model parameters in the parameter table. |
debug |
Logical. If TRUE, show debugging information. |
box_fast |
Logical. If |
con |
An optional partable where the operator is one of ‘==’, ‘>’, ‘<’ or ‘:=’ |
txt_only |
Logical. If TRUE, only the body of the function is returned as a character string. If FALSE, a function is returned. |
warn |
Logical. If FALSE, warnings are suppressed. |
Details
This is a collection of lower-level constraint-related functions that are used in the lavaan code. They are made public at the request of package developers. Below is a brief description of what they do:
The lav_con_parse function parses the constraints
specification (provided as a string, see example), and generates
a list with useful information about the constraints.
The lav_pt_con_ceq function creates a function
which takes the (unconstrained) parameter vector as input, and
returns the slack values for each equality constraint. If the equality
constraints hold perfectly, this function returns zeroes.
The lav_pt_con_ciq function creates a function
which takes the (unconstrained) parameter vector as input, and
returns the slack values for each inequality constraint.
The lav_pt_con_def function creates a function
which takes the (unconstrained) parameter vector as input, and
returns the computed values of the defined parameters.
Examples
myModel <- 'x1 ~ a*x2 + b*x3 + c*x4'
myParTable <- lavParTable(myModel, as_data_frame = FALSE)
con <- ' a == 2*b
b - c == 5 '
conInfo <- lav_con_parse(myParTable, constraints = con)
myModel2 <- 'x1 ~ a*x2 + b*x3 + c*x4
a == 2*b
b - c == 5 '
ceq <- lav_pt_con_ceq(partable = lavParTable(myModel2))
ceq( c(2,3,4) )
lavaan data functions
Description
Utility functions related to the Data slot
Usage
# update data slot with new data (of the same size)
lav_data_update(lavdata = NULL, new_x = NULL, boot_idx = NULL, boot_clus = NULL,
lavoptions = NULL, ...)
Arguments
lavdata |
A lavdata object. |
new_x |
A list of (new) data matrices (per group) of the same size. They replace the data stored in the internal data slot. |
boot_idx |
A list of integers. If bootstrapping was used to produce the data in newX, use these indices to adapt the remaining slots. |
boot_clus |
A list of integer matrices (per group), or NULL. For a cluster bootstrap of two-level data, the (relabeled) cluster ids of the resampled rows, used to adapt the multilevel (Lp) slots. |
lavoptions |
A named list. The Options slot from a lavaan object. |
... |
To accept old argument names with dots or capitals. No other arguments are accepted. |
Examples
# generate syntax for an independence model
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
# extract data slot and options
lavdata <- fit@Data
lavoptions <- lavInspect(fit, "options")
# create bootstrap sample
boot.idx <- sample(x = nobs(fit), size = nobs(fit), replace = TRUE)
newX <- list(lavdata@X[[1]][boot.idx,])
# generate update lavdata object
newdata <- lav_data_update(lavdata = lavdata, new_x = newX,
lavoptions = lavoptions)
Summarizing EFA Fits
Description
S3 summary and print methods for class efaList.
Usage
lav_efalist_summary(object,
nd = 3L, cutoff = 0.3, dot_cutoff = 0.1, alpha_level = 0.01,
lambda = TRUE, theta = TRUE, psi = TRUE, fit_table = TRUE,
fs_determinacy = FALSE, eigenvalues = TRUE, sumsq_table = TRUE,
lambda_structure = FALSE, se = FALSE, zstat = FALSE,
pvalue = FALSE, ...)
lav_efalist_summary_print(x, nd = 3L, cutoff = 0.3, dot_cutoff = 0.1,
alpha_level = 0.01, ...)
Arguments
object |
An object of class |
x |
An object of class |
nd |
Integer. The number of digits that are printed after the decimal point in the output. |
cutoff |
Numeric. Factor loadings smaller than this value (in absolute value) are not printed (even if they are significantly different from zero). The idea is that only medium to large factor loadings are printed, to better see the overall structure. |
dot_cutoff |
Numeric. Factor loadings larger (in absolute value) than this value, but smaller (in absolute value) than the cutoff value are shown as a dot. They represent small loadings that may still need your attention. |
alpha_level |
Numeric. If the p-value of a factor loading is smaller
than this value, a significance star is printed to the right of the
factor loading. To switch this off, use |
lambda |
Logical. If |
theta |
Logical. If |
psi |
Logical. If |
fit_table |
Logical. If |
fs_determinacy |
Logical. If |
eigenvalues |
Logical. If |
sumsq_table |
Logical. If |
lambda_structure |
Logical. If |
se |
Logical. If |
zstat |
Logical. If |
pvalue |
Logical. If |
... |
Further arguments passed to or from other methods. |
Value
The function lav_efalist_summary computes and returns a list of
summary statistics for the list of EFA models in object.
Examples
## The famous Holzinger and Swineford (1939) example
fit <- efa(data = HolzingerSwineford1939,
ov_names = paste("x", 1:9, sep = ""),
nfactors = 1:3,
rotation = list("geomin", geomin_epsilon = 0.01, rstarts = 1))
summary(fit, nd = 3L, cutoff = 0.2, dot_cutoff = 0.05,
lambda_structure = TRUE, pvalue = TRUE)
lav_export_estimation
Description
lavaan provides a range of optimization methods with the optim_method argument
(nlminb, BFGS, L-BFGS-B, GN, and nlminb_constr). 'lav_export_estimation'
allows exporting objects and functions necessary to pass a lavaan model into
any optimizer that takes a combination of (1) starting values, (2) fit-function,
(3) gradient-function, and (4) upper and lower bounds. This allows testing new
optimization frameworks.
Usage
lav_export_estimation(lavaan_model)
Arguments
lavaan_model |
a fitted lavaan model |
Value
List with:
get_coef - When equality constraints are present, lavaan applies internal transformations. get_coef is a function that reconstructs the output of the coef function for the parameters.
starting_values - starting_values to be used in the optimization
objective_function - objective function, expecting the current parameter values and the lavaan model
gradient_function - gradient function, expecting the current parameter values and the lavaan model
lower - lower bounds for parameters
upper - upper bound for parameters
Examples
library(lavaan)
model <- '
# latent variable definitions
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + y2 + y3 + y4
dem65 =~ y5 + a*y6 + y7 + y8
# regressions
dem60 ~ ind60
dem65 ~ ind60 + dem60
'
fit <- sem(model,
data = PoliticalDemocracy,
do_fit = FALSE)
est <- lav_export_estimation(lavaan_model = fit)
# The starting values are:
est$starting_values
# Note that these do not have labels (and may also differ from coef(fit)
# in case of equality constraints):
coef(fit)
# To get the same parameters, use:
est$get_coef(parameter_values = est$starting_values,
lavaan_model = fit)
# The objective function can be used to compute the fit at the current estimates:
est$objective_function(parameter_values = est$starting_values,
lavaan_model = fit)
# The gradient function can be used to compute the gradients at the current estimates:
est$gradient_function(parameter_values = est$starting_values,
lavaan_model = fit)
# Together, these elements provide the means to estimate the parameters with a large
# range of optimizers. For simplicity, here is an example using optim:
est_fit <- optim(par = est$starting_values,
fn = est$objective_function,
gr = est$gradient_function,
lavaan_model = fit,
method = "BFGS")
est$get_coef(parameter_values = est_fit$par,
lavaan_model = fit)
# This is identical to
coef(sem(model,
data = PoliticalDemocracy))
# Example using ridge regularization for parameter a
fn_ridge <- function(parameter_values, lavaan_model, est, lambda){
return(est$objective_function(parameter_values = parameter_values,
lavaan_model = lavaan_model) + lambda * parameter_values[6]^2)
}
ridge_fit <- optim(par = est$get_coef(est$starting_values,
lavaan_model = fit),
fn = fn_ridge,
lavaan_model = fit,
est = est,
lambda = 10)
est$get_coef(parameter_values = ridge_fit$par,
lavaan_model = fit)
Utility Functions: Gradient and Jacobian
Description
Utility functions for computing the gradient of a scalar-valued function or the Jacobian of a vector-valued function by numerical approximation.
Usage
lav_func_grad_complex(func, x, h = .Machine$double.eps, ...,
fallback_simple = TRUE)
lav_func_jacobian_complex(func, x, h = .Machine$double.eps, ...,
fallback_simple = TRUE)
lav_func_grad_simple(func, x, h = sqrt(.Machine$double.eps), ...)
lav_func_jacobian_simple(func, x, h = sqrt(.Machine$double.eps), ...)
Arguments
func |
A real-valued function returning a numeric scalar or a numeric vector. |
x |
A numeric vector: the point(s) at which the gradient/Jacobian of the function should be computed. |
h |
Numeric value representing a small change in ‘x’ when computing the gradient/Jacobian. |
... |
Additional arguments to be passed to the function ‘func’. |
fallback_simple |
Logical. If TRUE, and the function evaluation fails, we call the corresponding simple (non-complex) method instead. |
Details
The complex versions use complex numbers to gain more precision, while retaining the simplicity (and speed) of the simple forward method (see references). These functions were added to lavaan (around 2012), when the complex functionality was not yet part of the numDeriv package. They were used internally, and made public in 0.5-17 at the request of other package developers.
References
Squire, W. and Trapp, G. (1998). Using Complex Variables to Estimate Derivatives of Real Functions. SIAM Review, 40(1), 110-112.
Examples
# very accurate complex method
lav_func_grad_complex(func = exp, x = 1) - exp(1)
# less accurate forward method
lav_func_grad_simple(func = exp, x = 1) - exp(1)
# very accurate complex method
diag(lav_func_jacobian_complex(func = exp, x = c(1,2,3))) - exp(c(1,2,3))
# less accurate forward method
diag(lav_func_jacobian_simple(func = exp, x = c(1,2,3))) - exp(c(1,2,3))
Utility Functions For Covariance Matrices
Description
Convenience functions to deal with covariance and correlation matrices.
Usage
lav_getcov(x, lower = TRUE, diagonal = TRUE, sds = NULL,
names = paste("V", 1:nvar, sep=""))
getCov(x, lower = TRUE, diagonal = TRUE, sds = NULL,
names = paste("V", 1:nvar, sep=""))
lav_char2num(s)
char2num(s)
lav_cor2cov(r, sds, names = NULL, ...)
cor2cov(r, sds, names = NULL, ...)
Arguments
x |
The elements of the covariance matrix. Either inside a character
string or as a numeric vector. In the former case, the function
|
lower |
Logical. If |
diagonal |
Logical. If |
sds |
A numeric vector containing the standard deviations to be
used to scale the elements in |
names |
The variable names of the observed variables. |
s |
Character string containing numeric values; commas and semi-colons are ignored. |
r |
A correlation matrix, to be scaled into a covariance matrix. |
... |
To accept old argument name |
Details
The lav_getcov function is typically used to input the lower
(or upper) triangular elements of a (symmetric) covariance matrix. In many
examples found in handbooks, only those elements are shown. However, lavaan
needs a full matrix to proceed.
The lav_cor2cov function is the inverse of the cov2cor
function, and scales a correlation matrix into a covariance matrix given
the standard deviations of the variables. Optionally, variable names can
be given.
Examples
# The classic Wheaton et. al. (1977) model
# panel data on the stability of alienation
lower <- '
11.834,
6.947, 9.364,
6.819, 5.091, 12.532,
4.783, 5.028, 7.495, 9.986,
-3.839, -3.889, -3.841, -3.625, 9.610,
-21.899, -18.831, -21.748, -18.775, 35.522, 450.288 '
# convert to a full symmetric covariance matrix with names
wheaton.cov <- lav_getcov(lower, names=c("anomia67","powerless67", "anomia71",
"powerless71","education","sei"))
# the model
wheaton.model <- '
# measurement model
ses =~ education + sei
alien67 =~ anomia67 + powerless67
alien71 =~ anomia71 + powerless71
# equations
alien71 ~ alien67 + ses
alien67 ~ ses
# correlated residuals
anomia67 ~~ anomia71
powerless67 ~~ powerless71
'
# fitting the model
fit <- sem(wheaton.model, sample_cov=wheaton.cov, sample_nobs=932)
# showing the results
summary(fit, standardized=TRUE)
Provides a formatted label for use in tikz, svg or Rplot
Description
Creates the code used to show the label in tikz, svg or R. The label is plotted in an xy-plot if show = TRUE.
Usage
lav_label_code(label = "", value = "", show =FALSE,
idx_font_size = 20L, dy = 7L,
italic = TRUE, auto_subscript = TRUE)
Arguments
label |
A character string in one of the formats
If value is specified in parameter |
value |
A character string specifying a value or empty. |
show |
A logical indicating that the result should be plotted in an Rplot. |
idx_font_size |
An integer specifying font size to use for the subscript in svg. |
dy |
An integer specifying the distance to move the baseline of the subscript in svg. |
italic |
A logical indicating whether the label's font should be italic. Only used for tikz output and in the displayed Rplot when the result is not an expression. |
auto_subscript |
Logical, if TRUE and |
Details
If both label and value are empty, the resulting codes are
also empty and nothing will be shown.
If label is empty and value is not, processing is done as if
label was specified and value was empty.
If label contains the string "1van", the label value is set to "1".
This allows distinct names for regression intercepts while still labeling
them as "1".
If name in label is a Greek character or varepsilon,
the function attempts to generate code that shows the Greek symbol. If
label contains an index part, the function attempts to generate
code that displays this value as a subscript. In the svg code, the values
idx_font_size and dy are used for the subscript. If a
value is present, the function attempts to show this value after the
label, with an equal sign between the two.
Value
a list with members svg, tikz and r, giving the result.
Examples
lav_label_code("x3")
lav_label_code("beta10", 0.65, show = TRUE)
lav_label_code("A_i,j=0.45", show = TRUE)
lav_label_code("Gamma")
lav_label_code(value="1.2345")
Deprecated functions with long names
Description
Functions that are deprecated following the adoption of shorter names in May 2026.
Usage
lav_matrix_duplication_ginv_pre_post(A = matrix(0, 0, 0))
lav_matrix_orthogonal_complement(A = matrix(0, 0, 0))
lav_func_gradient_complex(
func,
x,
h = .Machine$double.eps,
...,
fallback.simple = TRUE)
lav_matrix_duplication_ginv_post(A = matrix(0, 0, 0))
lav_func_gradient_simple(
func,
x,
h = sqrt(.Machine$double.eps),
...)
lav_matrix_vech_row_idx(n = 1L, diagonal = TRUE)
lav_matrix_vech_col_idx(n = 1L, diagonal = TRUE)
lav_matrix_antidiag_idx(n = 1L)
lav_matrix_duplication_pre_post(A = matrix(0, 0, 0))
lav_matrix_duplication_ginv_pre(A = matrix(0, 0, 0))
lav_matrix_commutation_pre_post(A = matrix(0, 0, 0))
lav_partable_unrestricted(
lavobject = NULL,
lavdata = NULL,
lavpta = NULL,
lavoptions = NULL,
lavsamplestats = NULL,
lavh1 = NULL,
sample.cov = NULL,
sample.mean = NULL,
sample.slopes = NULL,
sample.th = NULL,
sample.th.idx = NULL,
sample.cov.x = NULL,
sample.mean.x = NULL)
lav_partable_independence(
lavobject = NULL,
lavdata = NULL,
lavpta = NULL,
lavoptions = NULL,
lavsamplestats = NULL,
lavh1 = NULL,
sample.cov = NULL,
sample.mean = NULL,
sample.slopes = NULL,
sample.th = NULL,
sample.th.idx = NULL,
sample.cov.x = NULL,
sample.mean.x = NULL)
lav_matrix_vechru_idx(n = 1L, diagonal = TRUE)
lav_matrix_upper2full(x, diagonal = TRUE)
lav_matrix_lower2full(x, diagonal = TRUE)
lav_matrix_commutation_mn_pre(
A,
m = 1L,
n = 1L)
lav_samplestats_from_data(
lavdata = NULL,
lavoptions = NULL,
WLS.V = NULL,
NACOV = NULL)
lav_matrix_vechru_reverse(x, diagonal = TRUE)
lav_matrix_vechr_idx(n = 1L, diagonal = TRUE)
lav_matrix_vechu_idx(n = 1L, diagonal = TRUE)
lav_matrix_diagh_idx(n = 1L)
lav_partable_attributes(partable, pta = NULL)
lav_matrix_vechr_reverse(x, diagonal = TRUE)
lav_matrix_vechu_reverse(x, diagonal = TRUE)
lav_matrix_vech_idx(n = 1L, diagonal = TRUE)
lav_matrix_diag_idx(n = 1L)
lav_matrix_duplication_post(A = matrix(0, 0, 0))
lav_matrix_duplication_ginv(n = 1L)
lav_matrix_commutation_post(A = matrix(0, 0, 0))
lav_matrix_symmetric_sqrt(S = matrix(0, 0, 0))
lav_matrix_vech_reverse(x, diagonal = TRUE)
lav_matrix_duplication_pre(A = matrix(0, 0, 0))
lav_matrix_commutation_pre(A = matrix(0, 0, 0))
lav_partable_complete(partable = NULL, start = TRUE)
lav_matrix_vechru(S, diagonal = TRUE)
lav_partable_constraints_def(
partable,
con = NULL,
debug = FALSE,
txtOnly = FALSE,
warn = TRUE)
lav_partable_constraints_ceq(
partable,
con = NULL,
debug = FALSE,
txtOnly = FALSE)
lav_partable_constraints_ciq(
partable,
con = NULL,
debug = FALSE,
txtOnly = FALSE)
lav_partable_from_lm(
object,
est = FALSE,
label = FALSE,
as.data.frame. = FALSE)
lav_constraints_parse(
partable = NULL,
constraints = NULL,
theta = NULL,
debug = FALSE)
lav_matrix_vechr(S, diagonal = TRUE)
lav_matrix_vechu(S, diagonal = TRUE)
lav_matrix_bdiag(...)
lav_matrix_trace(..., check = TRUE)
lav_partable_labels(
partable,
blocks = c("group", "level"),
group.equal = "",
group.partial = "",
type = "user")
lav_matrix_vecr(A)
lav_matrix_vech(S, diagonal = TRUE)
lav_partable_merge(
pt1 = NULL,
pt2 = NULL,
remove.duplicated = FALSE,
fromLast = FALSE,
warn = TRUE)
lav_matrix_vec(A)
lav_matrix_duplication(n = 1L)
lav_matrix_commutation(m = 1L, n = 1L)
lav_matrix_cov(Y, Mu = NULL)
lav_partable_ndat(partable)
lav_partable_npar(partable)
lav_partable_add(partable = NULL, add = list())
lav_partable_df(partable)
Arguments
... |
See argument |
A |
See argument |
add |
See argument |
as.data.frame. |
See argument |
blocks |
See argument |
check |
See argument |
con |
See argument |
constraints |
See argument |
debug |
See argument |
diagonal |
See argument |
est |
See argument |
fallback.simple |
See argument |
fromLast |
See argument |
func |
See argument |
group.equal |
See argument |
group.partial |
See argument |
h |
See argument |
label |
See argument |
lavdata |
See argument |
lavh1 |
See argument |
lavobject |
See argument |
lavoptions |
See argument |
lavpta |
See argument |
lavsamplestats |
See argument |
m |
See argument |
Mu |
See argument |
n |
See argument |
NACOV |
See argument |
object |
See argument |
partable |
See argument |
pt1 |
See argument |
pt2 |
See argument |
pta |
See argument |
remove.duplicated |
See argument |
S |
See argument |
sample.cov |
See argument |
sample.cov.x |
See argument |
sample.mean |
See argument |
sample.mean.x |
See argument |
sample.slopes |
See argument |
sample.th |
See argument |
sample.th.idx |
See argument |
start |
See argument |
theta |
See argument |
txtOnly |
See argument |
type |
See argument |
warn |
See argument |
WLS.V |
See argument |
x |
See argument |
Y |
See argument |
Details
Function names are shortened by the following replacements:
- _mvnorm
_mvn
- _cluster
_cl
- _missing
_mi
- _matrix
_mat
- _duplication
_dup
- _commutation
_com
- _information
_info
- _samplestats
_samp
- _satorra_bentler
_sb
- _SatorraBentler
_sb
- _yuan_bentler
_yb
- _inverted
_inv
- _estimate
_est
- _symmetric
_sym
- _lavaan_step
_step
- _univariate
_uni
- _fit_measures
_fit
- _constraints
_con
- _scores
_sc
- _reverse
_rev
- _vech_sigma
_sigma
- _vechsigma
_sigma
- _object_inspect
_inspect
- _orthogonal
_ortho
- _gradient
_grad
- _partable
_pt
Utility Functions: Matrices and Vectors
Description
Utility functions for Matrix and Vector operations.
Usage
# matrix to vector
lav_mat_vec(a)
lav_mat_vecr(a)
lav_mat_vech(s, diagonal = TRUE)
lav_mat_vechr(s, diagonal = TRUE)
# matrix/vector indices
lav_mat_vech_idx(n = 1L, diagonal = TRUE)
lav_mat_vech_row_idx(n = 1L, diagonal = TRUE)
lav_mat_vech_col_idx(n = 1L, diagonal = TRUE)
lav_mat_vechr_idx(n = 1L, diagonal = TRUE)
lav_mat_vechru_idx(n = 1L, diagonal = TRUE)
lav_mat_diag_idx(n = 1L)
lav_mat_diagh_idx(n = 1L)
lav_mat_antidiag_idx(n = 1L)
# vector to matrix
lav_mat_vech_rev(x, diagonal = TRUE)
lav_mat_vechru_rev(x, diagonal = TRUE)
lav_mat_upper2full(x, diagonal = TRUE)
lav_mat_vechr_rev(x, diagonal = TRUE)
lav_mat_vechu_rev(x, diagonal = TRUE)
lav_mat_lower2full(x, diagonal = TRUE)
# the duplication matrix
lav_mat_dup(n = 1L)
lav_mat_dup_pre(a = matrix(0,0,0))
lav_mat_dup_post(a = matrix(0,0,0))
lav_mat_dup_pre_post(a = matrix(0,0,0))
lav_mat_dup_ginv(n = 1L)
lav_mat_dup_ginv_pre(a = matrix(0,0,0))
lav_mat_dup_ginv_post(a = matrix(0,0,0))
lav_mat_dup_ginv_pre_post(a = matrix(0,0,0))
# the commutation matrix
lav_mat_com(m = 1L, n = 1L)
lav_mat_com_pre(a = matrix(0,0,0))
lav_mat_com_post(a = matrix(0,0,0))
lav_mat_com_pre_post(a = matrix(0,0,0))
lav_mat_com_mn_pre(a, m = 1L, n = 1L)
# sample statistics
lav_mat_cov(y, mu = NULL)
# other matrix operations
lav_mat_sym_sqrt(s = matrix(0,0,0))
lav_mat_ortho_complement(a = matrix(0,0,0))
lav_mat_bdiag(...)
lav_mat_trace(..., check = TRUE)
Arguments
a |
A general matrix. |
s |
A symmetric matrix. |
y |
A matrix representing a (numeric) dataset. |
diagonal |
Logical. If TRUE, include the diagonal. |
n |
Integer. When it is the only argument, the dimension of a square matrix. If m is also provided, the number of columns of the matrix. |
m |
Integer. The number of rows of a matrix. |
x |
Numeric. A vector. |
mu |
Numeric. If given, use mu (instead of sample mean) to center, before taking the crossproduct. |
... |
One or more matrices, or a list of matrices. |
check |
Logical. If |
Details
These are a collection of lower-level matrix and vector functions that are used throughout the lavaan code. They are made public at the request of package developers. Below is a brief description of what they do:
The lav_mat_vec function implements the vec operator (for
'vectorization') and transforms a matrix into a vector by stacking the
columns of the matrix one underneath the other.
The lav_mat_vecr function is similar to the lav_mat_vec
function but transforms a matrix into a vector by stacking the
rows of the matrix one underneath the other.
The lav_mat_vech function implements the vech operator
(for 'half vectorization') and transforms a symmetric matrix
into a vector by stacking the columns of the matrix one underneath the
other, but eliminating all supradiagonal elements. If diagonal = FALSE,
the diagonal elements are also eliminated.
The lav_mat_vechr function is similar to the lav_mat_vech
function but transforms a matrix into a vector by stacking the
rows of the matrix one underneath the other, eliminating all
supradiagonal elements.
The lav_mat_vech_idx function returns the vector indices of the lower
triangular elements of a symmetric matrix of size n, column by column.
The lav_mat_vech_row_idx function returns the row indices of the
lower triangular elements of a symmetric matrix of size n.
The lav_mat_vech_col_idx function returns the column indices of the
lower triangular elements of a symmetric matrix of size n.
The lav_mat_vechr_idx function returns the vector indices of the
lower triangular elements of a symmetric matrix of size n, row by row.
The lav_mat_vechu_idx function returns the vector indices of the
upper triangular elements of a symmetric matrix of size n, column by column.
The lav_mat_vechru_idx function returns the vector indices
of the upper triangular elements of a symmetric matrix of size n, row by row.
The lav_mat_diag_idx function returns the vector indices of the
diagonal elements of a symmetric matrix of size n.
The lav_mat_diagh_idx function returns the vector indices of
the lower part of a symmetric matrix of size n.
The lav_mat_antidiag_idx function returns the vector indices of
the anti diagonal elements of a symmetric matrix of size n.
The lav_mat_vech_rev function (alias:
lav_mat_vechru_rev and lav_mat_upper2full) creates a
symmetric matrix, given only upper triangular elements, row by row. If
diagonal = FALSE, a diagonal with zero elements is added.
The lav_mat_vechr_rev (alias: lav_mat_vechu_rev and
lav_mat_lower2full) creates a symmetric matrix, given only the lower
triangular elements, row by row. If diagonal = FALSE, a diagonal with zero
elements is added.
The lav_mat_dup function generates the duplication matrix
for a symmetric matrix of size n. This matrix duplicates the elements in
vech(S) to create vec(S) (where S is symmetric). This matrix is very
sparse, and should probably never be explicitly created. Use one of
the functions below.
The lav_mat_dup_pre function computes the product of the
transpose of the duplication matrix and a matrix A. The A matrix should have
n*n rows, where n is an integer. The duplication matrix is not explicitly
created.
The lav_mat_dup_post function computes the product of a
matrix A with the duplication matrix. The A matrix should have n*n columns,
where n is an integer. The duplication matrix is not explicitly created.
The lav_mat_dup_pre_post function first pre-multiplies a
matrix A with the transpose of the duplication matrix, and then post multiplies
the result again with the duplication matrix. A must be square matrix with n*n
rows and columns, where n is an integer. The duplication matrix is not
explicitly created.
The lav_mat_dup_ginv function computes the generalized
inverse of the duplication matrix. The matrix removes the duplicated elements
in vec(S) to create vech(S). This matrix is very sparse, and should probably
never be explicitly created. Use one of the functions below.
The lav_mat_dup_ginv_pre function computes the product of the
generalized inverse of the duplication matrix and a matrix A with n*n rows,
where n is an integer. The generalized inverse of the duplication matrix
is not explicitly created.
The lav_mat_dup_ginv_post function computes the product of a
matrix A (with n*n columns, where n is an integer) and the transpose of the
generalized inverse of the duplication matrix. The generalized inverse of the
duplication matrix is not explicitly created.
The lav_mat_dup_ginv_pre_post function first pre-multiplies
a matrix A with the transpose of the generalized inverse of the duplication
matrix, and then post multiplies the result again with the transpose of the
generalized inverse matrix. The matrix A must be square with n*n rows and
columns, where n is an integer. The generalized inverse of the duplication
matrix is not explicitly created.
The lav_mat_com function computes the commutation matrix, a
permutation matrix that transforms vec(A) (with m rows and n columns)
into vec(t(A)).
The lav_mat_com_pre function computes the product of the
commutation matrix with a matrix A, without explicitly creating the commutation
matrix. The matrix A must have n*n rows, where n is an integer.
The lav_mat_com_post function computes the product of a
matrix A with the commutation matrix, without explicitly creating the
commutation matrix. The matrix A must have n*n rows, where n is an integer.
The lav_mat_com_pre_post function first pre-multiplies
a matrix A with the commutation matrix, and then post multiplies the result again with the commutation matrix, without explicitly creating the
commutation matrix. The matrix A must have n*n rows, where n is an integer.
The lav_mat_com_mn_pre function computes the product of the
commutation matrix with a matrix A, without explicitly creating the commutation
matrix. The matrix A must have m*n rows, where m and n are integers.
The lav_mat_cov function computes the sample covariance matrix of
its input matrix, where the elements are divided by N (the number of rows).
The lav_mat_sym_sqrt function computes the square root of a
positive definite symmetric matrix (using an eigen decomposition). If some of
the eigenvalues are negative, they are silently fixed to zero.
The lav_mat_ortho_complement function computes an orthogonal
complement of the matrix A, using a qr decomposition.
The lav_mat_bdiag function constructs a block diagonal matrix from
its arguments.
The lav_mat_trace function computes the trace (the sum of the
diagonal elements) of a single (square) matrix, or if multiple matrices are
provided (either as a list, or as multiple arguments), we first compute their
product (which must result in a square matrix), and then we compute the trace;
if check = TRUE, we check if the (final) matrix is square.
References
Magnus, J. R. and H. Neudecker (1999). Matrix Differential Calculus with Applications in Statistics and Econometrics, Second Edition, John Wiley.
Examples
# upper elements of a 3 by 3 symmetric matrix (row by row)
x <- c(30, 16, 5, 10, 3, 1)
# construct full symmetric matrix
S <- lav_mat_upper2full(x)
# compute the normal theory `Gamma' matrix given a covariance
# matrix (S), using the formula: Gamma = 2 * D^{+} (S %x% S) t(D^{+})
Gamma.NT <- 2 * lav_mat_dup_ginv_pre_post(S %x% S)
Gamma.NT
lavaan model functions
Description
Utility functions related to internal model representation (lavmodel)
Usage
# set/get free parameters
lav_model_set_parameters(lavmodel, x = NULL)
lav_model_get_parameters(lavmodel, glist = NULL, type = "free",
extra = TRUE, ...)
# compute model-implied statistics
lav_model_implied(lavmodel, glist = NULL, delta = TRUE, ...)
# compute standard errors
lav_model_vcov_se(lavmodel, lavpartable, vcov = NULL, boot = NULL,
mc = NULL, lavoptions = NULL, ...)
Arguments
lavmodel |
An internal representation of a lavaan model. |
x |
Numeric. A vector containing the values of all the free model parameters. |
glist |
List. A list of model matrices, similar to the output of
|
type |
Character string. If |
extra |
Logical. If |
delta |
Logical. If |
lavpartable |
A parameter table. |
vcov |
Numeric matrix containing an estimate of the variance covariance matrix of the free model parameters. |
boot |
Numeric matrix containing the bootstrap based parameter estimates (in the columns) for each bootstrap sample (in the rows). |
mc |
Numeric matrix containing the Monte-Carlo based parameter estimates (in the columns) for each Monte-Carlo sample (in the rows). |
lavoptions |
A named list. The Options slot from a lavaan object. |
... |
To accept old argument names with dots or capitals. No other arguments are accepted. |
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
lavmodel <- fit@Model
est <- lav_model_get_parameters(lavmodel)
est
Get model information
Description
Extracts the information from a model that is needed to produce a plot.
Usage
lav_model_plotinfo(model = NULL, infile = NULL, varlv = FALSE)
Arguments
model |
A character vector specifying the model in lavaan syntax or a list
(or data.frame) with at least members lhs, op, rhs, label and fixed or a fitted
lavaan object (in which case the |
infile |
A character string specifying the file that contains the model syntax. |
varlv |
A logical indicating that the (residual) variance of a variable should be plotted as a separate latent variable (with a smaller circle than ordinary latent variables). In this case, a covariance between two such variables is plotted as a covariance between their variance latent variables. |
Value
A structure 'plotinfo', which is a list with members nodes and edges. These are data.frames containing the data needed to create a diagram.
nodes
- id
character, identification of the node consisting of blok and naam.
- naam
character, name of the node as specified in the model. For intercepts the name is "1vanXXXX", with XXXX the name of the regressed variable.
- tiepe
character, type of node: ov (observed variable), lv (latent variable), varlv (variance as latent variable), cv (composite variable), wov (within level variable in multilevel model), bov (between level variable in multilevel model), const (intercept of regression).
- blok
integer, level (0 if not a multilevel model).
edges
- id
integer, autoincrement identification of the edge.
- label
character, label for the edge, made from the label specified in the model and the fixed (or estimated) value if present.
- van
character, id of the starting node.
- naar
character, id of the destination node.
- tiepe
character, lavaan operator, with two exceptions: a (residual) variance is coded here as '~~~', and a regression introduced by varlv = TRUE is coded as '~.'.
Examples
model <- 'alpha =~ 1 * x1 + x2 + x3 # latent variable
beta <~ x4 + x5 + x6 # composite
gamma =~ 1 * x7 + x8 + x9 # latent variable
Xi =~ 1 * x10 + x11 + x12 + x13 # latent variable
# regressions
Xi ~ v * alpha + t * beta + cc * 1
alpha ~ tt * beta + ss * gamma + yy * Theta1
# variances and covariances
x2 ~~ cc25 * x5
x3 ~~ cc36 * x6
x3 ~~ cc34 * x4
gamma ~~ 0.55 * gamma
'
(test <- lav_model_plotinfo(model))
mplus to lavaan converter
Description
Read in an Mplus input file, convert it to lavaan syntax, and fit the model.
Usage
lav_mplus_lavaan(inpfile, run = TRUE)
mplus2lavaan(inpfile, run = TRUE)
Arguments
inpfile |
The filename (including a full path) of the Mplus input file. The data (as referred to in the Mplus input file) should be in the same directory as the Mplus input file. |
run |
Whether to run the specified Mplus input syntax ( |
Value
A lavaan object with the fitted results of the Mplus model. The parsed
and converted Mplus syntax is preserved in the @external slot of the lavaan
object in the $mplus.inp element. If run is FALSE, a list of converted
syntax is returned.
Author(s)
Michael Hallquist
See Also
Examples
## Not run:
out <- lav_mplus_lavaan("ex5.1.inp")
summary(out)
## End(Not run)
Convert Mplus model syntax to lavaan
Description
Converts Mplus model syntax into lavaan model syntax.
Usage
lav_mplus_syntax_model(syntax)
mplus2lavaan.modelSyntax(syntax)
Arguments
syntax |
A character vector containing Mplus model syntax to be
converted to lavaan model syntax. Note that parsing Mplus syntax often
requires correct usage of newline characters. If |
Value
A character string of converted lavaan model syntax.
Author(s)
Michael Hallquist
See Also
Examples
## Not run:
syntax <- '
f1 BY x1*1 x2 x3;
x1 WITH x2;
x3 (1);
x2 (1);
'
lavSyntax <- lav_mplus_syntax_model(syntax)
cat(lavSyntax)
## End(Not run)
lavaan partable functions
Description
Utility functions related to the parameter table (partable)
Usage
# extract information from a parameter table
lav_pt_df(partable)
lav_pt_ndat(partable)
lav_pt_npar(partable)
lav_pt_ngroups(partable)
lav_pt_attributes(partable, pta = NULL)
# generate parameter labels
lav_pt_labels(partable, blocks = c("group", "level"),
group_equal = "", group_partial = "", type = "user")
# generate parameter table for specific models
lav_pt_independence(lavobject = NULL, lavdata = NULL,
lavpta = NULL, lavoptions = NULL, lavsamplestats = NULL,
lavh1 = NULL,
sample_cov = NULL, sample_mean = NULL, sample_slopes = NULL,
sample_th = NULL, sample_th_idx = NULL,
sample_cov_x = NULL, sample_mean_x = NULL)
lav_pt_unrestricted(lavobject = NULL, lavdata = NULL,
lavpta = NULL, lavoptions = NULL, lavsamplestats = NULL,
lavh1 = NULL,
sample_cov = NULL, sample_mean = NULL, sample_slopes = NULL,
sample_th = NULL, sample_th_idx = NULL,
sample_cov_x = NULL, sample_mean_x = NULL)
lav_pt_from_lm(object, est = FALSE, label = FALSE,
as_data_frame = FALSE)
# complete a parameter table only containing a few columns (lhs,op,rhs)
lav_pt_complete(partable = NULL, start = TRUE)
# merge two parameter tables
lav_pt_merge(pt1 = NULL, pt2 = NULL, remove_duplicated = FALSE,
from_last = FALSE, warn = TRUE)
# add a single parameter to an existing parameter table
lav_pt_add(partable = NULL, add = list())
Arguments
partable |
A parameter table. See |
blocks |
Character vector. Which columns in the parameter table should be
taken to distinguish between different blocks of parameters (and hence
be given different labels)? If |
group_equal |
The same options can be used here as in the fitting functions. Parameters that are constrained to be equal across groups will be given the same label. |
group_partial |
A vector of character strings containing the labels of the parameters which should be free in all groups. |
type |
Character string. Either ‘user’ to select all entries, or ‘free’ to select only the free parameters from the parameter table. |
lavobject |
An object of class ‘lavaan’. If this argument is provided, it should be the only argument. All the values for the other arguments are extracted from this object. |
lavdata |
An object of class ‘lavData’. The Data slot from a lavaan object. |
lavoptions |
A named list. The Options slot from a lavaan object. |
lavsamplestats |
An object of class ‘lavSampleStats’. The SampleStats slot from a lavaan object. |
lavh1 |
A named list. The h1 slot from a lavaan object. |
lavpta |
The pta (parameter table attributes) slot from a lavaan object. |
sample_cov |
Optional list of numeric matrices. Each list element contains a sample variance-covariance matrix for this group. If provided, these values will be used as starting values. |
sample_mean |
Optional list of numeric vectors. Each list element contains a sample mean vector for this group. If provided, these values will be used as starting values. |
sample_slopes |
Optional list of numeric matrices.
Each list element contains the sample slopes for this group (only used
when |
sample_th |
Optional list of numeric vectors. Each list element contains a vector of sample thresholds for this group. If provided (and also sample.th.idx is provided), these values will be used as starting values. |
sample_th_idx |
Optional list of integers. Each list contains the threshold indices for this group. |
sample_cov_x |
Optional list of numeric matrices. Each list element
contains a sample variance-covariance matrix for the exogenous variables
for this group (only used when |
sample_mean_x |
Optional list of numeric vectors.
Each list element contains a sample mean vector for the exogenous variables
for this group (only used when |
est |
Logical. If TRUE, include the fitted estimates in the parameter table. |
label |
Logical. If TRUE, include parameter labels in the parameter table. |
as_data_frame |
Logical. If TRUE, return the parameter table as a data.frame. |
object |
An object of class |
start |
Logical. If TRUE, include a start column, based on the simple method for generating starting values. |
pta |
A list containing parameter attributes. |
pt1 |
A parameter table. |
pt2 |
A parameter table. |
remove_duplicated |
Logical. If |
from_last |
Logical. If |
warn |
Logical. If |
add |
A named list. A single row of a parameter table as a named list. |
Examples
# generate syntax for an independence model
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
lav <- lav_pt_independence(fit)
as.data.frame(lav, stringsAsFactors = FALSE)
# how many free parameters?
lav_pt_npar(lav)
# how many sample statistics?
lav_pt_ndat(lav)
Create diagram code for tikz or svg, or produce an R plot
Description
Creates code to draw a diagram in tikz or svg, plots the diagram, or stores the diagram in a png file.
Usage
lav_plot(model = NULL,
infile = NULL,
varlv = FALSE,
placenodes = NULL,
edgelabelsbelow = NULL,
group_covar_indicators = FALSE,
common_opts = list(sloped_labels = TRUE,
mlovcolors = c("lightgreen", "lightblue"),
italic = TRUE,
lightness = 1,
auto_subscript = TRUE),
rplot = list(outfile = "",
addgrid = TRUE),
tikz = list(outfile = "",
cex = 1.3,
standalone = FALSE),
svg = list(outfile = "",
stroke_width = 2L,
font_size = 20L,
idx_font_size = 15L,
dy = 5L,
font_family = "Latin Modern Math, arial, Arial, sans",
standalone = FALSE)
)
Arguments
model |
A character vector specifying the model in lavaan syntax or a list
(or data.frame) with at least members lhs, op, rhs, label and fixed or a fitted
lavaan object (in which case the |
infile |
A character string specifying the file that contains the model syntax. |
varlv |
A logical indicating that the (residual) variance of a variable should be plotted as a separate latent variable (with a smaller circle than ordinary latent variables). In this case, a covariance between two such variables is plotted as a covariance between their variance latent variables. |
placenodes |
optional list with members |
edgelabelsbelow |
optional list with members |
group_covar_indicators |
logical, should items with indicators which have an explicit covariance link be placed in the same group, i.e. forced to be on the same side of the diagram? |
common_opts |
options common to the three types of generated plots. |
rplot |
options for creating Rplot,
see |
tikz |
options for creating code for tikz plot,
see |
svg |
options for creating code for svg plot,
see |
Details
If rplot is specified, or if neither tikz nor svg is
specified, an R plot is generated, and stored in a png file if the outfile
member of rplot is set. If tikz is specified, the code for a tikz
diagram is stored in the specified outfile; the same applies to svg.
The lav_plot command tries to create a nice plot from the input model,
but the variable names should be kept short, and the nodes in the plot may
sometimes need to be rearranged. As an example, the (slightly modified) example
of the sem function in lavaan produces the first plot shown below.
Using the placenodes argument produces the second plot.
More details on the parameters can be found in the help for
the lav_... functions.
Value
NULL, invisible
See Also
lav_model_plotinfo, lav_plotinfo_positions,
lav_plotinfo_rgraph, lav_plotinfo_tikzcode,
lav_plotinfo_svgcode
Examples
model <- 'alpha11 =~ 1 * x1 + x2 + x3 # latent variable
alpha12 <~ x4 + x5 + x6 # composite
gamma =~ 1 * x7 + x8 + x9 # latent variable
xi =~ 1 * x10 + x11 + x12 + x13 # latent variable
x1 ~~ x3
x2 ~~ epsilon2 * x2
x12 ~~ epsilon12 * x12
x4 ~~ epsilon4 * x4
x7 ~~ x9
x10 ~~ x11 + x13
gamma ~~ 0.7 * xi
# regressions
xi ~ v * alpha11 + t * alpha12 + 1
alpha11 ~ yy * Theta1 + tt1 * 0.12 * alpha12 + ss * gamma
Theta1 ~~ alpha12
'
lav_plot(model)
lav_plot(model,
placenodes=list(Theta1 = c(2, 2.5)),
tikz = list(outfile=stdout()))
modelml <- '
level: 1
fw =~ y_1 + y_2 + y_3 + y_4
level: 2
fb =~ y_1 + y_2 + y_3 + y_5
y_2 ~~ cv24 * y_5
'
tikzcodeml <- lav_plot(modelml,
common_opts = list(auto_subscript = FALSE),
svg = list(outfile=stdout())
)
## Not run:
# example creating tex file with the above models
zz <- file("testtikz.tex", open="w")
writeLines(c(
'\documentclass{article}',
'\usepackage{amsmath, amssymb}',
'\usepackage{amsfonts}',
'\usepackage[utf8]{inputenc}',
'\usepackage[english]{babel}',
'\usepackage{xcolor}',
'\usepackage{color}',
'\usepackage{tikz}',
'\usetikzlibrary {shapes.geometric}',
'\begin{document}'),
zz)
lav_plot(model,
tikz = list(outfile = "tmp.tex")
)
tmp <- readLines("tmp.tex")
writeLines(tmp, zz)
writeLines(" ", zz)
lav_plot(modelml,
common_opts = list(sloped_labels = FALSE,
mlovcolors = c("lightgreen", "lightblue")),
tikz = list(outfile = "tmp.tex", cex = 1.4)
)
tmp <- readLines("tmp.tex")
writeLines(tmp, zz)
writeLines("\end{document}", zz)
close(zz)
openPDF <- function(f) {
os <- .Platform$OS.type
if (os=="windows")
shell.exec(normalizePath(f))
else {
pdf <- getOption("pdfviewer", default='')
if (nchar(pdf)==0)
stop("The 'pdfviewer' option is not set. Use options(pdfviewer=...)")
system2(pdf, args=c(f))
}
}
tools::texi2dvi("testtikz.tex", pdf = TRUE, clean = TRUE)
openPDF("testtikz.pdf")
# example creating html file with the above diagrams
zz <- file("demosvg.html", open="w")
writeLines(c(
'<!DOCTYPE html>',
'<html>',
'<body>',
'<h2>SVG diagrams created by lav_plot R package</h2>'),
zz)
lav_plot(model,
svg = list(outfile = "temp.svg")
)
tmp <- readLines("tmp.svg")
writeLines(tmp, zz)
writeLines("<br />", zz)
lav_plot(modelml,
common_opts = list(sloped_labels = FALSE),
tikz = list(outfile = "tmp.svg")
)
tmp <- readLines("tmp.svg")
writeLines(tmp, zz)
writeLines(c("</body>", "</html>"), zz)
close(zz)
browseURL("demosvg.html")
## End(Not run)
Position the nodes in the diagram
Description
Computes the positions for the nodes and anchors and control points for the edges in the diagram.
Usage
lav_plotinfo_positions(plotinfo,
placenodes = NULL,
edgelabelsbelow = NULL,
group_covar_indicators = FALSE,
debug = FALSE)
Arguments
plotinfo |
The plotinfo structure as returned from |
placenodes |
optional list with members |
edgelabelsbelow |
optional list with members |
group_covar_indicators |
logical, should items with indicators which have an explicit covariance link be placed in the same group, i.e. forced to be on the same side of the diagram? |
debug |
logical, print debug information? |
Details
This function tries to arrange the nodes and the anchor points for the
edges in a way that keeps the diagram reasonably compact, while placing the
dependent variable of a regression to the right of the variables it depends on.
If the result is not what you want, you can inspect the plot with the
lav_plotinfo_rgraph or lav_plot functions and then place some
nodes at a different location (placenodes) and/or move some edge labels
to the other side of the edge (labelsbelow).
For multilevel models – maximum two levels – the nodes in block 2 are grouped
at the top of the diagram and those in block 1 at the bottom. The item
mlrij gives the position of the separation between the blocks.
Value
A plotinfo structure with modified nodes and edges
data.frames, and an integer mlrij giving the position at which a line
should be drawn for multilevel models.
The data.frames have new columns defined as follows:
-
nodes- rij
index of the row where the node will be placed, initialized NA.
- kolom
index of the column where the node will be placed, initialized NA.
-
edges- vananker
character, anchor point for starting node, initialized NA.
- naaranker
character, anchor point for destination node, initialized NA.
- controlpt.kol
real, column position of control point if the edge has to be drawn as a quadratic Bezier curve.
- controlpt.row
real, row position of control point if the edge has to be drawn as a quadratic Bezier curve.
- labelbelow
logical, TRUE if label has to be positioned under the line, initialized FALSE.
See Also
lav_model_plotinfo, lav_plotinfo_rgraph,
lav_plot
Examples
model <- 'alfa =~ 1 * x1 + x2 + x3 # latent variable
beta <~ x4 + x5 + x6 # composite
gamma =~ 1 * x7 + x8 + x9 # latent variable
Xi =~ 1 * x10 + x11 + x12 + x13 # latent variable
# regressions
Xi ~ v * alfa + t * beta + cc * 1
alfa ~ tt * beta + ss * gamma + yy * Theta1
# variances and covariances
x2 ~~ cc25 * x5
x3 ~~ cc36 * x6
x3 ~~ cc34 * x4
gamma ~~ 0.55 * gamma
'
test <- lav_model_plotinfo(model)
(test_positioned <- lav_plotinfo_positions(test))
Plots a graph in R
Description
Creates a graph in R showing a simple diagram of the model.
Usage
lav_plotinfo_rgraph(plotinfo,
sloped_labels = TRUE,
outfile = "",
addgrid = TRUE,
mlovcolors = c("lightgreen", "lightblue"),
lightness = 1,
italic = TRUE,
auto_subscript = TRUE
)
Arguments
plotinfo |
A plotinfo structure as returned from |
sloped_labels |
Logical, should labels be sloped above (or below) the edges? |
outfile |
Character string naming the file in which to store the diagram as a PNG, or NA to show the plot in R. |
addgrid |
Logical, add a grid with indicated 'positions' to the graph? |
mlovcolors |
Array of two colors for distinguishing ov nodes with the same name across the levels of a multilevel model. |
lightness |
A scalar factor to modify the distances between nodes. |
italic |
Should labels be in an italic font? Attention: switching to an italic font is only possible if the label value is not an expression! |
auto_subscript |
Logical, see |
Value
NULL (invisible)
See Also
Examples
model <- 'alpha =~ x1 + x2 + x_3 # latent variable
beta <~ x4 + x5 + x6 # composite
gamma =~ x7 + x8 + x9 # latent variable
Xi =~ x10 + x11 + x12 + x13 # latent variable
# regressions
Xi ~ v * alpha + t * beta + c * 1
alpha ~ yy * Theta1 + tt * beta + ss * gamma
'
test <- lav_model_plotinfo(model)
test1 <- lav_plotinfo_positions(test)
lav_plotinfo_rgraph(test1, lightness = 1.1)
# better position for constant in regressen Xi, no sloped labels
test2 <- lav_plotinfo_positions(test, placenodes = list(`1vanXi` = c(2, 5)))
lav_plotinfo_rgraph(test2, FALSE, lightness = 1.1)
modelml <- '
level: 1
fw =~ 1*y_1 + y_2 + y_3 + y_5
level: 2
fb =~ 1*y_1 + y_2 + y_3 + y_4
y_2 ~~ cv24 * y_4
'
test <- lav_model_plotinfo(modelml)
test <- lav_plotinfo_positions(test)
lav_plotinfo_rgraph(test, sloped_labels = FALSE, addgrid = FALSE,
auto_subscript = FALSE)
## Not run:
# example where plot is stored in a PNG file
lav_plotinfo_rgraph(test, sloped_labels = FALSE, addgrid = FALSE,
auto_subscript = FALSE, outfile="demo_rplot.png")
## End(Not run)
Creates code to show a diagram in svg format
Description
Creates svg code to show a diagram of the model.
Usage
lav_plotinfo_svgcode(plotinfo,
outfile = "",
sloped_labels = TRUE,
standalone = FALSE,
stroke_width = 2L,
font_size = 20L,
idx_font_size = 15L,
dy = 5L,
mlovcolors = c("lightgreen", "lightblue"),
lightness= 1,
font_family = "Latin Modern Math, arial, Arial, sans",
italic = TRUE,
auto_subscript = TRUE
)
Arguments
plotinfo |
A plotinfo structure as returned from |
outfile |
A connection or a character string, the file to store the code. |
sloped_labels |
logical, sloped labels for the edges. |
standalone |
logical, should code be added to produce an html file with the svg embedded in it? If FALSE (the default), the outfile (if specified) must have the file extension 'svg'; if TRUE, the file extension must be 'htm' or 'html'. |
stroke_width |
Value for stroke-width parameter in svg. |
font_size |
An integer specifying the normal font size to use. |
idx_font_size |
An integer specifying the font size to use for a subscript. |
dy |
An integer specifying the distance by which to move the baseline of the subscript. |
mlovcolors |
Array of two colors for distinguishing ov nodes with the same name across the levels of a multilevel model. |
lightness |
A scalar factor to modify the distances between nodes. |
font_family |
Fonts to be tried for rendering the labels. The first one, Latin Modern Math, is close to the default font used in tikz for mathematical expressions and can be downloaded from CTAN. |
italic |
Should labels be in an italic font? If FALSE, the labels are shown in mathrm font. |
auto_subscript |
Logical, see |
Value
NULL (invisible)
See Also
Examples
model <- 'alpha =~ x1 + x2 + x3 # latent variable
beta <~ x4 + x5 + x6 # composite
gamma =~ x7 + x8 + x9 # latent variable
Xi =~ x10 + x11 + x12 + x13 # latent variable
# regressions
Xi ~ v * alpha + t * beta + 1
alpha ~ yy * Theta1 + tt * beta + ss * gamma
'
test <- lav_model_plotinfo(model)
test <- lav_plotinfo_positions(test)
lav_plotinfo_svgcode(test) # no file given, so output to R console
modelml <- '
level: 1
fw =~ 1*y_1 + y_2 + y_3 + y_5
level: 2
fb =~ 1*y_1 + y_2 + y_3 + y_4
y_2 ~~ cv24 * y_4
'
testml <- lav_model_plotinfo(modelml)
testml <- lav_plotinfo_positions(testml)
# in the line hereunder no file is given, so output to R console
lav_plotinfo_svgcode(testml, sloped_labels = FALSE, standalone = TRUE,
auto_subscript = FALSE)
## Not run:
# example creating html file with the above diagrams
zz <- file("demosvg.html", open="w")
writeLines(c(
'<!DOCTYPE html>',
'<html>',
'<body>',
'<h2>SVG diagrams created by lav_plot R package</h2>'),
zz)
lav_plotinfo_svgcode(test, outfile = "temp.svg")
tmp <- readLines("tmp.svg")
writeLines(tmp, zz)
writeLines("<br />", zz)
lav_plotinfo_svgcode(testml, outfile = "temp.svg", sloped_labels = FALSE,
standalone = TRUE)
tmp <- readLines("tmp.svg")
writeLines(tmp, zz)
writeLines(c("</body>", "</html>"), zz)
close(zz)
browseURL("demosvg.html")
## End(Not run)
Creates code to show a diagram in tikz format
Description
Creates the code to make a diagram in tikz.
Usage
lav_plotinfo_tikzcode(plotinfo,
outfile = "",
cex = 1.3,
sloped_labels = TRUE,
standalone = FALSE,
mlovcolors = c("lightgreen", "lightblue"),
lightness = 1,
italic = TRUE,
auto_subscript = TRUE
)
Arguments
plotinfo |
A plotinfo structure as returned from |
outfile |
A connection or a character string, the file to store the code. |
cex |
Minimum distance between nodes in cm. |
sloped_labels |
logical, sloped labels for the edges. |
standalone |
logical, should code be added to make the TeX file standalone? |
mlovcolors |
Array of two colors for distinguishing ov nodes with the same name across the levels of a multilevel model. |
lightness |
A scalar factor to modify the distances between nodes. |
italic |
Should labels be in an italic font? If FALSE, the labels are shown in mathrm font. |
auto_subscript |
Logical, see |
Value
NULL, invisible
See Also
Examples
model <- 'alpha =~ x1 + x2 + x3 # latent variable
beta <~ x4 + x5 + x6 # composite
gamma =~ x7 + x8 + x9 # latent variable
Xi =~ x10 + x11 + x12 + x13 # latent variable
# regressions
Xi ~ v * alpha + t * beta + 1
alpha ~ yy * Theta1 + tt * beta + ss * gamma
'
test <- lav_model_plotinfo(model)
test <- lav_plotinfo_positions(test)
lav_plotinfo_tikzcode(test) # no file given, so output to R console
modelml <- '
level: 1
fw =~ 1*y_1 + y_2 + y_3 + y_5
level: 2
fb =~ 1*y_1 + y_2 + y_3 + y_4
y_2 ~~ cv24 * y_4
'
testml <- lav_model_plotinfo(modelml)
testml <- lav_plotinfo_positions(testml)
# in the line hereunder no file is given, so output to R console
lav_plotinfo_tikzcode(testml, cex = 1.4, sloped_labels = FALSE,
standalone = TRUE, auto_subscript = FALSE)
## Not run:
# example creating tex file with the above diagrams
zz <- file("testtikz.tex", open="w")
writeLines(c(
'\documentclass{article}',
'\usepackage{amsmath, amssymb}',
'\usepackage{amsfonts}',
'\usepackage[utf8]{inputenc}',
'\usepackage[english]{babel}',
'\usepackage{xcolor}',
'\usepackage{color}',
'\usepackage{tikz}',
'\usetikzlibrary {shapes.geometric}',
'\begin{document}'),
zz)
lav_plotinfo_tikzcode(test, outfile = "temp.tex")
tmp <- readLines("tmp.tex")
writeLines(tmp, zz)
writeLines(" ", zz)
lav_plotinfo_tikzcode(testml, outfile = "temp.tex", cex = 1.4,
sloped_labels = FALSE, auto_subscript = FALSE)
tmp <- readLines("tmp.tex")
writeLines(tmp, zz)
writeLines("\end{document}", zz)
close(zz)
openPDF <- function(f) {
os <- .Platform$OS.type
if (os=="windows")
shell.exec(normalizePath(f))
else {
pdf <- getOption("pdfviewer", default='')
if (nchar(pdf)==0)
stop("The 'pdfviewer' option is not set. Use options(pdfviewer=...)")
system2(pdf, args=c(f))
}
}
tools::texi2dvi("testtikz.tex", pdf = TRUE, clean = TRUE)
openPDF("testtikz.pdf")
## End(Not run)
lavaan samplestats functions
Description
Utility functions related to the sample statistics
Usage
# generate samplestats object from full data
lav_samp_from_data(lavdata = NULL, lavoptions = NULL,
wls_v = NULL, nacov = NULL)
Arguments
lavdata |
A lavdata object. |
lavoptions |
A named list. The Options slot from a lavaan object. |
wls_v |
A user provided weight matrix. |
nacov |
A user provided matrix containing the elements of (N times) the asymptotic variance-covariance matrix of the sample statistics. For a multiple group analysis, a list with an asymptotic variance-covariance matrix for each group. |
Examples
# generate syntax for an independence model
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
# extract data slot and options
lavdata <- fit@Data
lavoptions <- lavInspect(fit, "options")
# generate sample statistics object
sampleStats <- lav_samp_from_data(lavdata = lavdata,
lavoptions = lavoptions)
Fit a Latent Variable Model
Description
Fit a latent variable model.
Usage
lavaan(model = NULL, data = NULL, ordered = NULL, aux = NULL,
sampling_weights = NULL,
sample_cov = NULL, sample_mean = NULL, sample_th = NULL,
sample_nobs = NULL,
group = NULL, cluster = NULL, panel = NULL, constraints = "",
wls_v = NULL, nacov = NULL, ov_order = "model",
sampling_weights_cluster = NULL,
slot_options = NULL, slot_par_table = NULL, slot_sample_stats = NULL,
slot_data = NULL, slot_model = NULL, slot_cache = NULL,
sloth1 = NULL,
...)
Arguments
model |
A description of the user-specified model. Typically, the model
is described using the lavaan model syntax. See
|
data |
An optional data frame containing the observed variables used in the model. If some variables are declared as ordered factors, lavaan will treat them as ordinal variables. |
ordered |
Character vector. Only used if the data is in a data.frame. Treat these variables as ordered (ordinal) variables, if they are endogenous in the model. Importantly, all other variables will be treated as numeric (unless they are declared as ordered in the data.frame.) Since 0.6-4, ordered can also be logical. If TRUE, all observed endogenous variables are treated as ordered (ordinal). If FALSE, all observed endogenous variables are considered to be numeric (again, unless they are declared as ordered in the data.frame.) |
aux |
Character vector. Names of auxiliary observed variables. Auxiliary
variables are not part of the user-specified model; they are used to make
the missing-at-random (MAR) assumption more plausible under missing data.
Only available (for now) with continuous data and one of
|
sampling_weights |
A variable name in the data frame containing
sampling weight information. Depending on the
|
sample_cov |
Numeric matrix. A sample variance-covariance matrix.
The rownames and/or colnames must contain the observed variable names.
For a multiple group analysis, a list with a variance-covariance matrix
for each group. If |
sample_mean |
A sample mean vector. For a multiple group analysis, a list with a mean vector for each group. |
sample_th |
Vector of sample-based thresholds. For a multiple group analysis, a list with a vector of thresholds for each group. |
sample_nobs |
Number of observations if the full data frame is missing and only sample moments are given. For a multiple group analysis, a list or a vector with the number of observations for each group. |
group |
Character. A variable name in the data frame defining the groups in a multiple group analysis. |
cluster |
Character. A (single) variable name in the data frame defining the clusters in a two-level dataset. |
panel |
Character. If the data are long panel data (one row per
person and occasion), the names of the id and the time variable, as in
|
constraints |
Additional (in)equality constraints not yet included in the
model syntax. See |
wls_v |
A user provided weight matrix to be used by estimator |
nacov |
A user provided matrix containing the elements of (N times)
the asymptotic variance-covariance matrix of the sample statistics.
For a multiple group analysis, a list with an asymptotic
variance-covariance matrix for each group. See the |
ov_order |
Character. If |
sampling_weights_cluster |
A variable name in the data frame containing
the sampling weights of the clusters (level-2 units). Only used for
two-level models (see the |
slot_options |
Options slot from a fitted lavaan object. If provided, no new Options slot will be created by this call. |
slot_par_table |
ParTable slot from a fitted lavaan object. If provided, no new ParTable slot will be created by this call. |
slot_sample_stats |
SampleStats slot from a fitted lavaan object. If provided, no new SampleStats slot will be created by this call. |
slot_data |
Data slot from a fitted lavaan object. If provided, no new Data slot will be created by this call. |
slot_model |
Model slot from a fitted lavaan object. If provided, no new Model slot will be created by this call. |
slot_cache |
Cache slot from a fitted lavaan object. If provided, no new Cache slot will be created by this call. |
sloth1 |
h1 slot from a fitted lavaan object. If provided, no new h1 slot will be created by this call. |
... |
Many more options can be specified, using 'name = value'.
See |
Value
An object of class lavaan, for which several methods
are available, including a summary method.
References
Yves Rosseel (2012). lavaan: An R Package for Structural Equation Modeling. Journal of Statistical Software, 48(2), 1-36. doi:10.18637/jss.v048.i02
See Also
Examples
# The Holzinger and Swineford (1939) example
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- lavaan(HS.model, data=HolzingerSwineford1939,
auto_var=TRUE, auto_fix_first=TRUE,
auto_cov_lv_x=TRUE)
summary(fit, fit_measures = TRUE)
Class For Representing A (Fitted) Latent Variable Model
Description
The lavaan class represents a (fitted) latent variable
model. It contains a description of the model as specified by the user,
a summary of the data, an internal matrix representation, and if the model
was fitted, the fitting results.
Objects from the Class
Objects can be created via the
cfa, sem, growth or
lavaan functions.
Slots
version:The lavaan package version used to create this object
call:The function call as returned by
match.call().timing:The elapsed time (user+system) for various parts of the program as a list, including the total time.
Options:Named list of options that were provided by the user, or filled-in automatically.
ParTable:Named list describing the model parameters. Can be coerced to a data.frame. In the documentation, this is called the ‘parameter table’.
pta:Named list containing parameter table attributes.
Data:Object of internal class
"Data": information about the data.SampleStats:Object of internal class
"SampleStats": sample statisticsModel:Object of internal class
"Model": the internal (matrix) representation of the modelCache:List of objects that are computed only once and reused many times.
Fit:Object of internal class
"Fit": the results of fitting the model. No longer used.boot:List. Results and information about the bootstrap.
optim:List. Information about the optimization.
loglik:List. Information about the loglikelihood of the model (if maximum likelihood was used).
implied:List. Model implied statistics.
vcov:List. Information about the variance matrix (vcov) of the model parameters.
test:List. Different test statistics.
h1:List. Information about the unrestricted h1 model (if available).
baseline:List. Information about a baseline model (often the independence model) (if available).
internal:List. For internal use only.
external:List. Empty slot to be used by add-on packages.
Methods
- coef
signature(object = "lavaan", type = "free"): Returns the estimates of the parameters in the model as a named numeric vector. Iftype="free", only the free parameters are returned. Iftype="user", all parameters listed in the parameter table are returned, including constrained and fixed parameters.- fitted.values
signature(object = "lavaan"): Returns the implied moments of the model as a list with two elements (per group):covfor the implied covariance matrix, andmeanfor the implied mean vector. If only the covariance matrix was analyzed, the implied mean vector will be zero.- fitted
signature(object = "lavaan"): an alias forfitted.values.- residuals
signature(object = "lavaan", type="raw"): Iftype = "raw", this function returns the raw (= unscaled) difference between the observed and the expected (model-implied) summary statistics. Iftype = "cor", ortype = "cor.bollen", the observed and model implied covariance matrices are first transformed to a correlation matrix (usingcov2cor()), before the residuals are computed. Iftype = "cor.bentler", both the observed and model implied covariance matrices are rescaled by dividing the elements by the square roots of the corresponding variances of the observed covariance matrix. Iftype="normalized", the residuals are divided by the square root of the asymptotic variance of the corresponding summary statistic (the variance estimate depends on the choice for theseargument). Unfortunately, these normalized residuals are not entirely correct, and this option is retained only for historical interest. Iftype="standardized", the residuals are divided by the square root of the asymptotic variance of these residuals. The resulting standardized residuals can be interpreted as z-scores. Iftype="standardized.mplus", the residuals are divided by the square root of the asymptotic variance of these residuals. However, a simplified formula is used (see the Mplus reference below) which often results in negative estimates for the variances, resulting in manyNAvalues for the standardized residuals.- resid
signature(object = "lavaan"): an alias forresiduals- vcov
signature(object = "lavaan", type = "free"): returns the covariance matrix of the estimated parameters. Iftype = "free"(the default), only the free parameters are included. Iftype = "user"(or"joint"), the joint covariance matrix of the free and the user-defined (:=) parameters is returned; the parameter names are the same as those used bycoef().- predict
signature(object = "lavaan"): compute factor scores for all cases that are provided in the data frame. For complete data only.- anova
signature(object = "lavaan"): returns model comparison statistics. This method is just a wrapper around the functionlavTestLRT. If only a single argument (a fitted model) is provided, this model is compared to the unrestricted model. If two or more arguments (fitted models) are provided, the models are compared in a sequential order. Test statistics are based on the likelihood ratio test. For more details and further options, see thelavTestLRTpage.- update
signature(object = "lavaan", model, add, ..., evaluate = TRUE): update a fitted lavaan object and evaluate it (unlessevaluate = FALSE). Note that we use the environment that is stored within the lavaan object, which is not necessarily the parent frame. Theaddargument is analogous to the one described in thelavTestScorepage, and can be used to add parameters to the specified model rather than passing an entirely newmodelargument.- nobs
signature(object = "lavaan"): returns the effective number of observations used when fitting the model. In a multiple group analysis, this is the sum of all observations per group.- logLik
signature(object = "lavaan"): returns the log-likelihood of the fitted model, if maximum likelihood estimation was used. TheAICandBICmethods automatically work vialogLik().- show
signature(object = "lavaan"): Print a short summary of the model fit- summary
signature(object = "lavaan", header = TRUE, fit_measures = FALSE, residuals = FALSE, estimates = TRUE, ci = FALSE, fmi = FALSE, standardized = FALSE, std = standardized, std_nox = FALSE, remove_system_eq = TRUE, remove_eq = TRUE, remove_ineq = TRUE, remove_def = FALSE, remove_nonfree = FALSE, remove_step1 = TRUE, remove_unused = TRUE, plabel = FALSE, cov_std = TRUE, rsquare = FALSE, baseline_model = NULL, h1_model = NULL, fm_args = list(standard_test = "default", scaled_test = "default", rmsea_ci_level = 0.90, rmsea_close_h0 = 0.05, rmsea_notclose_h0 = 0.08, robust = TRUE, cat_nonpd = "na"), modindices = FALSE, srmr_close_h0 = NULL, nd = 3L, cutoff = 0.3, dot_cutoff = 0.1): Print a nice summary of the model estimates. Ifheader = TRUE, the header section (including fit measures) is printed. Iffit_measures = TRUE, additional fit measures are added to the header section.fit_measurescan also be a list, which allows one to set options related to the fit measures. SeefitMeasuresfor more details. Ifresiduals = TRUE, a residuals section is added (the largest residuals and the residual summary, printed as bylavResidualswithoutput = "text"); the underlyinglavResiduals(object, output = "list")result is stored as theresidualselement of the summary object.residualscan also be a list of arguments passed on tolavResiduals(for exampleresiduals = list(type = "raw", n.largest = 10)). If bothfit_measures = TRUEandresiduals = TRUEand the residual summary is the SRMR (the default), the SRMR is removed from the fit measures section to avoid printing it twice. Ifestimates = TRUE, print the parameter estimates section. Ifci = TRUE, add confidence intervals to the parameter estimates section. Iffmi = TRUE, add the fmi (fraction of missing information) column, if it is available. Ifstandardized = TRUEor a character vector, the standardized solution is also printed (seelavParameterEstimates). Note that SEs and tests are still based on unstandardized estimates. UsestandardizedSolutionto obtain SEs and test statistics for standardized estimates. Thestd.noxargument is deprecated; thestandardizedargument allows"std.nox"solution to be specifically requested. Thestandardizedargument may also be a character vector of (observed) variable names (for examplec("x1", "x2")); only the parameters involving these variables are then standardized, and the result is shown in aStd.usrcolumn. This generalizes"std.nox", where the exogenousxvariables are the ones left unstandardized. Ifremove_system_eq = TRUE, the system-generated equality constraints (using plabels) are not shown. Ifremove_eq = TRUEorremove_ineq = TRUE, the user-specified (in)equality constraints are not shown. Ifremove_def = TRUE, the user-specified parameter definitions are not shown. Ifremove_nonfree = TRUE, the nonfree parameters are not shown. Ifremove_step1 = TRUE, the parameters of the measurement part are not shown (only used when usingsam().) Ifremove_unused = TRUE, automatically added parameters that are fixed to their default (0 or 1) values are removed. Ifrsquare = TRUE, the R-Square values for the dependent variables in the model are printed. Thefm.argslist allows one to set options related to the fit measures (seefitMeasures).baseline.modelandh1.modelallow one to specify user-defined baseline and/or h1 models for the fit measures. If the model is an exploratory factor analysis (EFA) model, EFA related information is printed automatically. Thecutoffanddot.cutoffarguments control how the factor loadings are displayed: loadings whose absolute value is at or abovecutoffare shown as numbers; loadings whose absolute value falls betweendot.cutoffandcutoffare replaced by a dot; loadings whose absolute value is belowdot.cutoffare left blank. Ifmodindices = TRUEormodindicesis a list, modification indices are printed for all fixed parameters. The argumentnddetermines the number of digits after the decimal point to be printed (currently only in the parameter estimates section.) Historically, nothing was returned, but since 0.6-12, a list is returned of classlavaan.summaryfor which a print function is available.
References
Yves Rosseel (2012). lavaan: An R Package for Structural Equation Modeling. Journal of Statistical Software, 48(2), 1-36. doi:10.18637/jss.v048.i02
Standardized Residuals in Mplus. Document retrieved from URL https://www.statmodel.com/download/StandardizedResiduals.pdf
See Also
cfa, sem,
fitMeasures, standardizedSolution,
lavParameterEstimates, lavInspect,
modindices
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data = HolzingerSwineford1939)
summary(fit, standardized = TRUE, fit_measures = TRUE, rsquare = TRUE)
fitted(fit)
coef(fit)
resid(fit, type = "normalized")
Deprecated functions in lavaan package
Description
Deprecated functions in lavaan.
Details
The functions listed in the first column below are deprecated; calls to them should be replaced by calls to the corresponding function in the second column.
| # bootstrapLavaan | lavBootstrap |
| char2num | lav_char2num |
| cor2cov | lav_cor2cov |
| getCov | lav_getcov |
| inspectSampleCov | lavInspectSampleCov |
| # lavaanNames | lavNames |
| mplus2lavaan.modelSyntax | lav_mplus_syntax_model |
| mplus2lavaan | lav_Mplus_lavaan |
| parameterestimates | lavParameterEstimates |
| # simulateData | lavSimulateData |
Fit List of Latent Variable Models
Description
Fit the same latent variable model to a (potentially large) number of datasets.
Usage
lavaanList(model = NULL, data_list = NULL, data_function = NULL,
data_function_args = list(), ndat = length(data_list), cmd = "lavaan",
..., store_slots = c("partable"), fun = NULL, show_progress = FALSE,
store_failed = FALSE, parallel = c("no", "multicore", "snow"),
ncpus = min(2L, max(1L, parallel::detectCores() - 1L, na.rm = TRUE)),
cl = NULL, iseed = NULL)
semList(model = NULL, data_list = NULL, data_function = NULL,
data_function_args = list(), ndat = length(data_list),
..., store_slots = c("partable"), fun = NULL, show_progress = FALSE,
store_failed = FALSE, parallel = c("no", "multicore", "snow"),
ncpus = min(2L, max(1L, parallel::detectCores() - 1L, na.rm = TRUE)),
cl = NULL, iseed = NULL)
cfaList(model = NULL, data_list = NULL, data_function = NULL,
data_function_args = list(), ndat = length(data_list),
..., store_slots = c("partable"), fun = NULL, show_progress = FALSE,
store_failed = FALSE, parallel = c("no", "multicore", "snow"),
ncpus = min(2L, max(1L, parallel::detectCores() - 1L, na.rm = TRUE)),
cl = NULL, iseed = NULL)
Arguments
model |
A description of the user-specified model. Typically, the model
is described using the lavaan model syntax. See
|
data_list |
List. Each element contains a full data frame containing the observed variables used in the model. |
data_function |
Function. A function that generates a full data frame containing the observed variables used in the model. It can also be a matrix, if the columns are named. |
data_function_args |
List. Optional list of arguments that are passed
to the |
ndat |
Integer. The number of datasets that should be generated using
the |
cmd |
Character. The command used to run the SEM models. The possible
choices are |
... |
Other named arguments for the |
store_slots |
Character vector. Which slots (from a lavaan object)
should be stored for each dataset? The possible choices are
|
fun |
Function. A function which when applied to the
|
store_failed |
Logical. If |
parallel |
The type of parallel operation to be used (if any). If
missing, the default is |
ncpus |
Integer. The number of processes to be used in parallel operation: By default, this is 2 (following CRAN policy). You may set this to a higher value (for example, the number of available CPUs) if you wish to use more processes. |
cl |
An optional parallel or snow cluster for use if
|
iseed |
An integer to set the seed. Or NULL if no reproducible seeds are
needed. To make this work, make sure the first
RNGkind() element is |
show_progress |
If |
Value
An object of class lavaanList, for which several methods
are available, including a summary method.
See Also
class lavaanList, lavSimulate
Examples
# The Holzinger and Swineford (1939) example
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
# a data generating function
generateData <- function() lavSimulateData(HS.model, sample_nobs = 100)
set.seed(1234)
fit <- semList(HS.model, data_function = generateData, ndat = 5,
store_slots = "partable")
# show parameter estimates, per dataset
coef(fit)
Class For Representing A List of (Fitted) Latent Variable Models
Description
The lavaanList class represents a collection of (fitted)
latent variable models, fitted to a (potentially large) number of datasets.
It contains information about the model (which is always the same),
and, for every dataset, a set of (user-specified) slots from a regular
lavaan object.
Objects from the Class
Objects can be created via the
cfaList, semList, or
lavaanList functions.
Slots
version:The lavaan package version used to create this object
call:The function call as returned by
match.call().Options:Named list of options that were provided by the user, or filled-in automatically.
ParTable:Named list describing the model parameters. Can be coerced to a data.frame. In the documentation, this is called the ‘parameter table’.
pta:Named list containing parameter table attributes.
Data:Object of internal class
"Data": information about the data.Model:Object of internal class
"Model": the internal (matrix) representation of the modelmeta:List containing additional flags. For internal use only.
timingList:List. Timing slot per dataset.
ParTableList:List. ParTable slot per dataset.
DataList:List. Data slot per dataset.
SampleStatsList:List. SampleStats slot per dataset.
CacheList:List. Cache slot per dataset.
vcovList:List. vcov slot per dataset.
testList:List. test slot per dataset.
optimList:List. optim slot per dataset.
impliedList:List. implied slot per dataset.
h1List:List. h1 slot per dataset.
loglikList:List. loglik slot per dataset.
baselineList:List. baseline slot per dataset.
funList:List. fun slot per dataset.
internalList:List. internal slot per dataset.
external:List. Empty slot to be used by add-on packages.
Methods
- coef
signature(object = "lavaanList", type = "free"): Returns the estimates of the parameters in the model as the columns in a matrix; each column corresponds to a different dataset. Iftype="free", only the free parameters are returned. Iftype="user", all parameters listed in the parameter table are returned, including constrained and fixed parameters.- summary
signature(object = "lavaanList", header = TRUE, estimates = TRUE, print = TRUE, nd = 3L, simulate_args = list(est_bias = TRUE, rel_bias = TRUE, rmse = TRUE, se_bias = TRUE, se_bias_med = TRUE, prop_sig = TRUE, coverage = TRUE, mcse = TRUE, standardized = TRUE, test = TRUE, fit_measures = TRUE, level = 0.95, trim = 0)): Print a summary of the collection of fitted models. Ifheader = TRUE, the header section is printed. Ifestimates = TRUE, print the parameter estimates section. Ifprint = TRUE, the summary is printed to the screen. The argumentnddetermines the number of digits after the decimal point to be printed (currently only in the parameter estimates section.) The argumentsimulate_argsis only used if the meta slot indicates that the parameter tables are obtained in the context of a simulation. The options switch on/off the columns that are printed, and thetrimoption determines the amount of trimming that is used when taking the average (or standard deviation) across all replications. Ifse_bias_med = TRUE(the default, only relevant whense_bias = TRUE), two additional columns are printed:se_med(the median, rather than the mean, of the computed standard errors across replications) andse_bias_med(the ratiose_med/se_obs). The median is a robust alternative to the mean-basedse_ave/se_bias, which can be dominated by a few outliers for nonlinear defined parameters (e.g. ratios with near-zero denominators in some replications). Ifrel_bias = TRUE, the relative bias (est_bias/est_true) is added; ifrmse = TRUE, the root mean squared error is added. Ifmcse = TRUE, the Monte Carlo standard errors of the bias (est_bias_mcse), of the ratiose_bias(se_bias_mcse) and of the coverage (coverage_mcse) are added. Iftest = TRUE, and the test statistics were stored, the average and the variance of each test statistic are shown, together with the proportion of datasets where the model is rejected at the 0.10, 0.05 and 0.01 level. Iffit_measures = TRUE, and fit measures were computed for each dataset, their average, standard deviation and the 5th, 50th and 95th percentile are shown. Ifstandardized = TRUE, and the standardized estimates were computed for each dataset, a second table with the same columns is shown for the standardized estimates. The dotted spelling (simulate.args,est.bias, ...) is still accepted. If some datasets could not be used (no convergence, an error, or empty response categories for an ordered variable), the header shows how many, and why.
See Also
cfaList, semList, lavaanList,
lavSimulate
The mimic= option
Description
The mimic= argument of the lavaan function (and its
wrappers cfa, sem and growth)
controls a collection of primarily technical default settings, with the aim of
making lavaan's output as similar as possible to that of other SEM software.
This applies in particular to a few key results, such as the value of the
Satorra-Bentler scaled test statistic.
The mimic= option was originally introduced to demonstrate that
differences between lavaan and other SEM programs were often due to technical
implementation details rather than errors in lavaan. Nevertheless, the scope of
the mimic= option is intentionally limited. It is designed to reproduce
a small number of important results and does not attempt to replicate every
quantity reported by alternative SEM software packages.
This help page documents which options are affected by the
mimic= argument.
Details
The mimic= argument does not change the model that is fitted, nor the
estimator that is used. Instead, it overwrites the default values of a number
of (mostly technical) options that are otherwise estimator-dependent. The
user can always override these defaults by setting the corresponding option
explicitly in the lavaan call.
The argument is case-insensitive and accepts a number of aliases. After normalization, only four values remain:
"lavaan":the native lavaan defaults (also selected by the value
"default"); this is the default."Mplus":mimic the
Mplusprogram (also selected by the value"mplus")."EQS":mimic the
EQSprogram (also selected by the values"eqs","LISREL"and"lisrel")."lm":a minimal setting used internally for plain regression (also selected by the value
"regression"); not intended for general use.
mimic = "lavaan" (the default)
This is the reference setting. For maximum likelihood (ML) estimation, the following defaults are used:
likelihood = "normal":the sample covariance matrix is rescaled by a factor
(N-1)/N, so the loglikelihood and standard errors are based on a division byN(rather thanN-1).conditional_x = FALSE:the exogenous
xcovariates are regressed out first, and a conditional (on x) model is fitted.fixed_x = TRUE:the means, variances and covariances of the exogenous
xcovariates are fixed to their sample values (for the ML, MML and IV estimator groups, unlessstart = "simple").zero_keep_margins = TRUE:for categorical data, the (one-way) margins are preserved when adding a small constant to empty cells.
In addition, the various Mplus-specific technical options
(information_expected_mplus, gamma_vcov_mplus,
gamma_wls_mplus, gls_v11_mplus and
rmsea_scaled_mplus) are all set to FALSE.
mimic = "Mplus"
Starting from the lavaan defaults, the following options are changed in an
attempt to reproduce the output of Mplus:
information_expected_mplus = TRUE:use the Mplus variant of the expected information matrix. This affects the standard errors (when
information = "expected") and the scaled (Satorra-Bentler and Yuan-Bentler) test statistics.gamma_vcov_mplus = TRUE:use the Mplus way of computing the
\Gammamatrix (the asymptotic covariance matrix of the sample statistics) that enters the robust (sandwich) standard errors.gamma_wls_mplus = TRUE:use the Mplus way of computing the
\Gammamatrix used as the weight matrix in (D)WLS estimation.gls_v11_mplus = TRUE:use the Mplus variant of the weight matrix used in GLS estimation (when there is a meanstructure and
conditional_x = FALSE).rmsea_scaled_mplus = TRUE:use the Mplus reference distribution for the scaled RMSEA confidence interval and p-values. lavaan refers the unscaled test statistic to a chi-square distribution with
tr[U\Gamma]degrees of freedom, while Mplus refers the scaled statistic to a chi-square distribution with the degrees of freedom of the scaled test. Both match the mean of the null distribution, but on a different scale, so they yield different intervals and p-values. This only affects the Satorra-Bentler and Yuan-Bentler family (MLM,MLR,MLMVS,WLSM, ...); for the shifted family (MLMV,WLSMV,ULSMV) lavaan already uses the Mplus convention.missing = "ml":for continuous data and the ML or MLR estimator, the default missing-data handling becomes full information maximum likelihood (FIML), rather than listwise deletion.
meanstructure = TRUE:a meanstructure is added by default (unless the estimator is PML).
group_equal:in a multiple-group analysis, if no equality constraints are requested, a default set is imposed:
"loadings"and"thresholds"for categorical data;"loadings"for continuous data without a meanstructure; and"loadings"and"intercepts"for continuous data with a meanstructure.baseline_conditional_x_free_slopes = FALSE:when
conditional_x = TRUE, the baseline (independence) model does not free the slope structure.- mixed numeric/ordinal data:
in the three-stage (D)WLS approach, the asymptotic covariance matrix of the sample statistics (and the (D)WLS weight matrix) involves the matrix of derivatives of the stage-1/2 estimating equations. For the numeric variables, lavaan uses the analytic information (means, slopes, variances) and the observed second-order derivatives of the bivariate (pearson, polyserial) loglikelihoods, which remain valid if the numeric variables are not normally distributed. Mplus (and lavaan before 0.7-3) replaces all these derivatives by crossproducts of the scores (the information identity), which is only valid under normality of the numeric variables. For purely ordinal data, both approaches coincide.
The likelihood, conditional_x, fixed_x and
zero_keep_margins defaults are the same as for
mimic = "lavaan".
mimic = "EQS"
Starting from the lavaan defaults, the following options are changed in an
attempt to reproduce the output of EQS (the value "LISREL" is
treated as an alias for "EQS"):
likelihood = "wishart":for ML estimation, the Wishart likelihood is used. The sample covariance matrix is divided by
N-1(instead ofN), which affects the chi-square test statistic, the loglikelihood and the standard errors.fixed_x = FALSE:the exogenous
xcovariates are treated as random variables: their means, variances and covariances are freely estimated (rather than fixed to their sample values).baseline_fixed_x_free_cov = FALSE:the covariances among the exogenous covariates are constrained to zero in the baseline (independence) model, just like all other covariances. By default, they are retained (freely estimated if
fixed_x = FALSE, fixed to their sample values iffixed_x = TRUE), which yields a smaller baseline chi-square statistic.
In addition, for the MLR estimator, the robust test statistic defaults to
"yuan.bentler" (instead of the "yuan.bentler.mplus" variant
that is used for mimic = "lavaan" and mimic = "Mplus").
The conditional_x and zero_keep_margins defaults are the same
as for mimic = "lavaan".
Note that the mimic= argument only sets defaults: any option
that is set explicitly in the lavaan call takes precedence. The
mimicking is also necessarily incomplete; small numerical differences with
the target program may remain.
See Also
Examples
# default (mimic = "lavaan")
fit1 <- cfa(" visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 ",
test = "satorra.bentler",
missing = "listwise",
data = HolzingerSwineford1939)
fit1
# mimic the Mplus program
fit2 <- cfa(" visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 ",
test = "satorra.bentler",
missing = "listwise",
data = HolzingerSwineford1939, mimic = "Mplus")
fit2
# mimic the EQS program
fit3 <- cfa(" visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 ",
test = "satorra.bentler",
missing = "listwise",
data = HolzingerSwineford1939, mimic = "EQS")
fit3
The Lavaan Model Syntax
Description
The lavaan model syntax describes a latent variable model. The
function lavParTable turns it into a table that represents the full
model as specified by the user. We refer to this table as the parameter table.
Usage
lavaanify(model = NULL, meanstructure = FALSE, int_ov_free = FALSE,
int_lv_free = FALSE, marker_int_zero = FALSE,
orthogonal = FALSE, orthogonal_y = FALSE,
orthogonal_x = FALSE, orthogonal_efa = FALSE, std_lv = FALSE,
correlation = FALSE, correlation_delta_free = FALSE,
composites = TRUE, composites_cov_free = FALSE,
effect_coding = "", conditional_x = FALSE,
fixed_x = FALSE, parameterization = "Delta", constraints = NULL,
ceq_simple = FALSE, auto = FALSE, model_type = "sem",
auto_fix_first = FALSE, marker = NULL,
auto_fix_single = FALSE, auto_var = FALSE,
auto_cov_lv_x = FALSE, auto_cov_x = FALSE, auto_cov_y = FALSE,
auto_cov_rv = FALSE, auto_th = FALSE, auto_delta = FALSE, auto_efa = FALSE,
var_table = NULL, ngroups = 1L, nthresholds = NULL,
group_equal = NULL, group_partial = NULL, group_w_free = FALSE,
debug = FALSE, warn = TRUE, as_data_frame = TRUE, ...)
lavParTable(model = NULL, meanstructure = FALSE, int_ov_free = FALSE,
int_lv_free = FALSE, marker_int_zero = FALSE,
orthogonal = FALSE, orthogonal_y = FALSE,
orthogonal_x = FALSE, orthogonal_efa = FALSE, std_lv = FALSE,
correlation = FALSE, correlation_delta_free = FALSE,
composites = TRUE, composites_cov_free = FALSE,
effect_coding = "", conditional_x = FALSE,
fixed_x = FALSE, parameterization = "Delta", constraints = NULL,
ceq_simple = FALSE, auto = FALSE, model_type = "sem",
auto_fix_first = FALSE, marker = NULL,
auto_fix_single = FALSE, auto_var = FALSE,
auto_cov_lv_x = FALSE, auto_cov_x = FALSE, auto_cov_y = FALSE,
auto_cov_rv = FALSE, auto_th = FALSE, auto_delta = FALSE, auto_efa = FALSE,
var_table = NULL, ngroups = 1L, nthresholds = NULL,
group_equal = NULL, group_partial = NULL, group_w_free = FALSE,
debug = FALSE, warn = TRUE, as_data_frame = TRUE, ...)
lavParseModelString(model_syntax = '', as_data_frame = FALSE,
parser = "open", warn = TRUE, debug = FALSE, ...)
Arguments
model |
A description of the user-specified model. Typically, the model
is described using the lavaan model syntax; see details for more
information. Alternatively, a parameter table (e.g., the output of
|
model_syntax |
The model syntax specifying the model. Must be a literal string. |
meanstructure |
If |
int_ov_free |
If |
int_lv_free |
If |
marker_int_zero |
Logical. Only relevant if the metric of each latent
variable is set by fixing the first factor loading to unity.
If |
orthogonal |
If |
orthogonal_y |
If |
orthogonal_x |
If |
orthogonal_efa |
If |
std_lv |
If |
correlation |
If |
correlation_delta_free |
Logical. Only used if
|
composites |
Logical. If |
composites_cov_free |
Logical. Only relevant if the model contains
composites. If |
effect_coding |
Can be logical or character string. If
logical and |
conditional_x |
If |
fixed_x |
If |
parameterization |
Currently only used if data is categorical. If
|
constraints |
Additional (in)equality constraints. See details for more information. |
ceq_simple |
If |
auto |
If |
model_type |
Either |
auto_fix_first |
If |
marker |
Optional named character vector mapping a latent variable
(name) to the observed indicator (name) whose loading should be fixed to
1.0 (instead of the first indicator) when |
auto_fix_single |
If |
auto_var |
If |
auto_cov_lv_x |
If |
auto_cov_x |
If |
auto_cov_y |
If |
auto_cov_rv |
If |
auto_th |
If |
auto_delta |
If |
auto_efa |
If |
var_table |
The variable table containing information about the observed variables in the model. |
ngroups |
The number of (independent) groups. |
nthresholds |
Either a single integer or a named vector of integers.
If |
group_equal |
A vector of character strings. Only used in
a multiple group analysis. Can be one or more of the following:
|
group_partial |
A vector of character strings containing the labels of the parameters which should be free in all groups (thereby overriding the group_equal argument for some specific parameters). |
group_w_free |
Logical. If |
as_data_frame |
If |
parser |
Character. If |
warn |
If |
debug |
If |
... |
To accept old argument names with dots. No other arguments are accepted. |
Details
The model syntax consists of one or more formula-like expressions, each one
describing a specific part of the model. The model syntax can be read from
a file (using readLines), or can be specified as a literal
string enclosed by single quotes as in the example below.
myModel <- '
# 1. latent variable definitions
f1 =~ y1 + y2 + y3
f2 =~ y4 + y5 + y6
f3 =~ y7 + y8 +
y9 + y10
f4 =~ y11 + y12 + y13
! this is also a comment
# 2. regressions
f1 ~ f3 + f4
f2 ~ f4
y1 + y2 ~ x1 + x2 + x3
# 3. (co)variances
y1 ~~ y1
y2 ~~ y4 + y5
f1 ~~ f2
# 4. intercepts
f1 ~ 1; y5 ~ 1
# 5. thresholds
y11 | t1 + t2 + t3
y12 | t1
y13 | t1 + t2
# 6. scaling factors
y11 ~*~ y11
y12 ~*~ y12
y13 ~*~ y13
# 7. composites
f5 <~ z1 + z2 + z3 + z4
'
Blank lines and comments can be used in between the formulas, and formulas can be split over multiple lines. Both the sharp (#) and the exclamation (!) characters can be used to start a comment. Multiple formulas can be placed on a single line if they are separated by a semicolon (;).
A formula continues on the next line when a line ends with an operator
(+, -, *, /, ^, ++, a comma, an
opening parenthesis, or any of the lavaan operators such as =~ or
:=), or when the next line starts with +, ++, *,
a closing parenthesis, or a lavaan operator. A semicolon always ends a
formula. Variable names that contain spaces (or other special characters)
must be quoted, with single or double quotes ("my var" =~ x1 + 'x 2');
two names separated only by spaces are an error. In constraints, >=
and <= may be used as synonyms of > and <. Characters
that look like an operator but are different characters (full-width forms,
the small tilde, the minus sign and the en dash, ‘smart’ quotes, no-break
spaces), as produced by word processors or web pages, are read as the
corresponding ASCII character; inside quoted names they are left as they are.
There can be seven types of formula-like expressions in the model syntax:
Latent variable definitions: The
"=~"operator can be used to define (continuous) latent variables. The name of the latent variable is on the left of the"=~"operator, while the terms on the right, separated by"+"operators, are the indicators of the latent variable.The operator
"=~"can be read as “is manifested by”.Regressions: The
"~"operator specifies a regression. The dependent variable is on the left of a"~"operator and the independent variables, separated by"+"operators, are on the right. These regression formulas are similar to the way ordinary linear regression formulas are used in R, but they may include latent variables. Interaction terms are currently not supported.Variance-covariances: The
"~~"(‘double tilde’) operator specifies (residual) variances of an observed or latent variable, or a set of covariances between one variable and several other variables (either observed or latent). Several variables, separated by"+"operators, can appear on the right. In this way, several pairwise (co)variances involving the same left-hand variable can be expressed in a single expression. The distinction between variances and residual variances is made automatically.Intercepts: A special case of a regression formula can be used to specify an intercept (or a mean) of either an observed or a latent variable. The variable name is on the left of a
"~"operator, and the only term on the right is the number"1", representing the intercept. Including an intercept formula in the model automatically impliesmeanstructure = TRUE. The distinction between intercepts and means is made automatically.Thresholds: The
"|"operator can be used to define the thresholds of categorical endogenous variables (on the left-hand side of the operator). By convention, the thresholds (on the right-hand side, separated by the"+"operator) are named"t1","t2", and so on.Scaling factors: The
"~*~"operator defines a scale factor. The variable name on the left hand side must be the same as the variable name on the right hand side. Scale factors are used in the Delta parameterization, in a multiple group analysis when factor indicators are categorical. Note that the interpretation of a scale factor depends on the setting: for a categorical variable (underparameterization = "Theta"), it equals the reciprocal (1/sd) of the standard deviation of the latent response variable (scaling its covariance matrix down to a correlation matrix); for a continuous variable undercorrelation = TRUEwith an ML-family estimator, it equals the marginal (model-implied) standard deviation itself (scaling the unit-diagonal correlation structure up to a covariance matrix). The two settings never occur within the same model.Composites: The
"<~"operator can be used to define a composite (on the right hand side of the operator). A composite is a weighted linear combination of its composite indicators. The name of the composite variable is on the left of the"<~"operator, while the terms on the right, separated by"+"operators, are the indicators of the composite variable.
There are 4 additional operators, also with left- and right-hand sides, that can
be included in model syntax. Three of them are used to specify (in)equality
constraints on estimated parameters (==, >, and <), and
those are demonstrated in a later section about
(In)equality constraints.
The final additional operator (:=) can be used to define “new” parameters
that are functions of one or more other estimated parameters. The :=
operator is demonstrated in a section about User-defined parameters.
Usually, only a single variable name appears on the left side of an
operator. However, if multiple variable names are specified,
separated by the "+" operator, the formula is repeated for each
element on the left side (as for example in the third regression
formula in the example above). The only exception is scaling factors, where
only a single element is allowed on the left-hand side.
In the right-hand side of these formula-like expressions, each element can be
modified (using the "*" operator) by either a numeric constant,
an expression resulting in a numeric constant, an expression resulting
in a character vector, or one
of three special functions: start(), label() and equal().
This provides the user with a mechanism to fix parameters, to provide
alternative starting values, to label the parameters, and to define equality
constraints among model parameters. All "*" expressions are
referred to as modifiers. They are explained in more detail in the
following sections.
Fixing parameters
It is often desirable to fix a model parameter that is otherwise (by default) free. Any parameter in a model can be fixed by using a modifier resulting in a numerical constant. Here are some examples:
Fixing the regression coefficient of the predictor
x2:y ~ x1 + 2.4*x2 + x3
Specifying an orthogonal (zero) covariance between two latent variables:
f1 ~~ 0*f2
Specifying an intercept and a linear slope in a growth model:
i =~ 1*y11 + 1*y12 + 1*y13 + 1*y14 s =~ 0*y11 + 1*y12 + 2*y13 + 3*y14
Instead of a numeric constant, one can use a mathematical function that returns
a numeric constant, for example sqrt(10). Multiplying with NA
will force the corresponding parameter to be free.
Additionally, the == operator can be used to set a labeled parameter
equal to a specific numeric value. This will be demonstrated in the section below
about (In)equality constraints.
Starting values
User-provided starting values can be given by using the special function
start(), containing a numeric constant. For example:
y ~ x1 + start(1.0)*x2 + x3
Note that if a starting value is provided, the parameter is not automatically considered to be free.
Parameter labels and equality constraints
Each free parameter in a model is automatically given a name (or label).
The name given to a model
parameter consists of three parts, coerced to a single character vector.
The first part is the name of the variable in the left-hand side of the
formula where the parameter was
implied. The middle part is based on the special ‘operator’ used in the
formula. This can be either one of "=~", "~" or "~~". The
third part is the name of the variable in the right-hand side of the formula
where the parameter was implied, or "1" if it is an intercept. The three
parts are pasted together in a single string. For example, the name of the
fixed regression coefficient in the regression formula
y ~ x1 + 2.4*x2 + x3 is the string "y~x2".
The name of the parameter
corresponding to the covariance between two latent variables in the
formula f1 ~~ f2 is the string "f1~~f2".
Although this automatic labeling of parameters is convenient, the user may
specify their own labels for specific parameters simply by pre-multiplying
the corresponding term (on the right hand side of the operator only) by
a character string (starting with a letter).
For example, in the formula f1 =~ x1 + x2 + mylabel*x3, the parameter
corresponding with the factor loading of
x3 will be named "mylabel".
An alternative way to specify the label is as follows:
f1 =~ x1 + x2 + label("mylabel")*x3,
where the label is the argument of special function label();
this can be useful if the label contains a space, or an operator (like "~").
There are two ways to constrain a parameter
to be equal to another target parameter. If you
have specified your own labels, you can use the fact that
equal labels imply equal parameter values.
If you rely on automatic parameter labels, you
can use the special function equal(). The argument of
equal() is the (automatic or user-specified) name of the target
parameter. For example, in the confirmatory factor analysis example below, the
intercepts of the three indicators of each latent variable are constrained to
be equal to each other. For the first three, we have used the default
names. For the last three, we have provided a custom label for the
y2a intercept.
model <- '
# two latent variables with fixed loadings
f1 =~ 1*y1a + 1*y1b + 1*y1c
f2 =~ 1*y2a + 1*y2b + 1*y2c
# intercepts constrained to be equal
# using the default names
y1a ~ 1
y1b ~ equal("y1a~1") * 1
y1c ~ equal("y1a~1") * 1
# intercepts constrained to be equal
# using a custom label
y2a ~ int2*1
y2b ~ int2*1
y2c ~ int2*1
'
Multiple groups
In a multiple group analysis, modifiers that contain a single element should be replaced by a vector, having the same length as the number of groups. If you provide a single element, it will be recycled for all the groups. This may be dangerous, in particular when the modifier is a label. In that case, the (same) label is copied across all groups, and this would imply an equality constraint across groups. Therefore, when using modifiers in a multiple group setting, it is always safer (and cleaner) to specify the same number of elements as the number of groups. Consider this example with two groups:
HS.model <- ' visual =~ x1 + 0.5*x2 + c(0.6, 0.8)*x3
textual =~ x4 + start(c(1.2, 0.6))*x5 + x6
speed =~ x7 + x8 + c(x9.group1, x9.group2)*x9 '
In this example, the factor loading of the ‘x2’ indicator is fixed to the value 0.5 for both groups. However, the factor loadings of the ‘x3’ indicator are fixed to 0.6 and 0.8 for group 1 and group 2 respectively. The same logic is used for all modifiers. Note that character vectors can contain unquoted strings.
Multiple modifiers
In the model syntax, you can specify a variable more than once on the right hand side of an operator; therefore, several ‘modifiers’ can be applied simultaneously; for example, if you want to fix the value of a parameter and also label that parameter, you can use something like:
f1 =~ x1 + x2 + 4*x3 + x3.loading*x3
Variable series (the ++ operator)
Long lists of variable names that only differ by a number or a letter can be
abbreviated with the "++" operator. The expression "x1 ++ x5"
is equivalent to "x1 + x2 + x3 + x4 + x5". The series runs from the
first name to the last name, and may be descending as well: "x5 ++ x1"
is equivalent to "x5 + x4 + x3 + x2 + x1". The two endpoints must have
the same structure: the parts that differ must be either numbers (possibly
with leading zeros, as in "x01 ++ x10") or single letters (as in
"xa ++ xd"), and the parts that are the same must match exactly. If
several parts differ, they must all change by the same amount, so that
"x1y1 ++ x3y3" expands to "x1y1 + x2y2 + x3y3". A series can
appear anywhere a list of names separated by "+" is allowed, on the
right-hand side as well as on the left-hand side of an operator, and it can
be combined with ordinary terms or with other series:
f1 =~ x1 ++ x5 + x8 f2 =~ y01 ++ y10 f3 =~ z9 ++ z1 f1 ++ f3 ~ w1 ++ w4
Modifiers may be attached to the endpoints of a series. A numeric constant or a label that is identical for both endpoints is applied to every element; a label that itself forms a series is expanded along with the variable names:
f1 =~ a*x1 ++ a*x5 # all loadings equal (labeled a) f2 =~ b1*y1 ++ b5*y5 # labels b1, b2, b3, b4, b5 f3 =~ 1*z1 ++ 1*z5 # all loadings fixed to 1
Indexed names (repeated measures)
Models for repeated measures in wide format (one column per variable and
per wave, as in x1, x2, x3, x4) contain many
statements that only differ by the wave. An index in square brackets
writes such a family of statements once. The index is bound to a
range of integers in one place of a statement (x[t in 1:4]), and can
be referred to elsewhere in the same statement, possibly with an
integer offset (x[t], x[t-1], x[t+1]). The statement
then stands for one copy per value of the index, in which each indexed name
is written with the value after it. For example,
wx[t in 2:4] ~ wx[t-1] + wy[t-1]
is equivalent to
wx2 ~ wx1 + wy1 wx3 ~ wx2 + wy2 wx4 ~ wx3 + wy3
A random-intercept cross-lagged panel model for two variables measured at four waves can thus be written as:
RIx =~ 1*x[t in 1:4] RIy =~ 1*y[t in 1:4] wx[t in 1:4] =~ 1*x[t] wy[t in 1:4] =~ 1*y[t] x[t in 1:4] ~~ 0*x[t] y[t in 1:4] ~~ 0*y[t] wx[t in 2:4] ~ wx[t-1] + wy[t-1] wy[t in 2:4] ~ wx[t-1] + wy[t-1] wx[t in 1:4] ~~ wx[t] + wy[t] wy[t in 1:4] ~~ wy[t] RIx ~~ RIx + RIy RIy ~~ RIy RIx + RIy ~~ 0*wx1 + 0*wy1
The last line fixes the covariances between the random intercepts and the
within-person components of the first wave to zero. Without it, sem()
would free these four covariances among exogenous latent variables.
Labels are names, and can carry an index as well. A label without an index
is repeated in every copy, which implies an equality constraint across the
waves; a label with an index gives one label per wave:
wx[t in 2:4] ~ a*wx[t-1] # labels a, a, a: equal effects wx[t in 2:4] ~ a[t]*wx[t-1] # labels a2, a3, a4: free effects a[t in 2:3] == a[t+1] # equality written as constraints d[t in 2:3] := a[t+1] - a[t] # one defined parameter per wave
Inside a modifier (or in a constraint or a definition), a bound index used
as a number stands for its value. This gives, for example, the fixed time
scores of a growth model: s =~ (t-1)*y[t in 1:5] fixes the loadings
to 0, 1, 2, 3, 4. A bare index as the whole modifier (t*y[t]) would
read as a label, and is not allowed; write fixed(t)*y[t] instead.
The rules are as follows. (1) An index is bound once per statement, on any
name of the statement; several indices may be bound, and the copies then
run over all combinations of their values. (2) A range lo:hi is
ascending. A bound may also be an index bound earlier in the same
statement, alone or with an integer offset in parentheses, as in
x1_[s in 1:2] ~~ x1_[t in (s+1):3] (which gives each pair once); such
a dependent range that comes out empty generates nothing. (3) The value is
written directly after the name in front of the bracket: x1_[t]
gives x1_3; there is no space between a name and its index, and no
text after the index. If the lower bound of a range is written with a
leading zero, all names use that width: y[t in 03:10] ~ y[t-1] gives
y03 ~ y02, ..., y10 ~ y09. (4) Nothing is dropped
silently: a range that is too wide generates names that do not exist (such
as wx0), and lavaan reports them as such. (5) An endpoint of the
++ operator can not be an indexed name, and a quoted name is never
expanded. Indexed names are only available in the default parser
(parser = "open"). For data in long format (one row per person and
occasion), the panel= argument of lavaan reshapes the
data to this wide format, so that the same syntax can be used.
Lagged variables in long data (two-level models). With
panel = c(id = "pid", time = "day") and a two-level model (with
level: 1 and level: 2 blocks), the data are not reshaped:
each row is an occasion, and the id variable is the cluster variable. An
index that is not bound then refers to the time variable of the
data: y[t-1] is the value of y at the previous occasion of the
same person, y[t-2] the value two occasions earlier (and
y[t+1] the next one). For example, a bivariate first-order
(vector) autoregressive model with random intercepts:
level: 1 y ~ y[t-1] + x[t-1] x ~ x[t-1] + y[t-1] y ~~ x level: 2 y ~~ y + x x ~~ x
The lagged variables are created in the data, with the names
y.lag1, x.lag1 (or y.lead1 for y[t+1]), under
which they appear in the output; the lag column of the parameter
table contains 1 for y ~ y.lag1. The lags follow the values of the
time variable (which must contain integers): if an occasion is missing, the
lagged value at the next occasion is missing too. Occasions without the
values of the lagged predictors (the first occasion of each person, and the
first occasion after a gap) are not used. A name without index is the
value at the current occasion. A random autoregressive effect is written
with the rv() modifier, as in y ~ rv("phi")*y[t-1] (see
Random slopes above).
These lagged variables are observed variables at the within level: they
are not centered, and the likelihood is conditional on them (and on
all other observed within-only covariates), as in lme4::lmer() with
a lagged predictor, or in Mplus with lagged variables computed by hand and
declared as WITHIN variables (ESTIMATOR = ML). The first
occasion of each person is conditioned upon, but the random intercept is
assumed to be independent of it, although in an autoregressive process it
is not (the 'initial condition' problem, which matters mostly for short
series); a common remedy is to add the first observed value of y of
each person as a between-level covariate. This differs from the dynamic
structural equation models (DSEM) of Mplus, which decompose the lagged
variables into latent within and between parts (latent centering) and use
Bayesian estimation. Lagged variables in long data require estimator
"ML" or "MLR" and continuous data (missing = "ml" is
supported); as for random slopes, no chi-square test statistic is computed,
but the loglikelihood and information criteria are available.
For each element of the parameter table that is generated from a statement
in which the left- and the right-hand side carry the same index, the
column lag of the parameter table contains the difference between
the index values of the two sides: 1 for wx2 ~ wx1, 0 for
wx2 ~~ wy2, and NA for all other elements. The column is only
present if the syntax contains indexed names.
Two-level models
In a two-level model (with a cluster= argument), the model syntax
contains a separate block for each level. A block starts with the
level: block identifier, followed by a number or a label:
level: 1 fw =~ y1 + y2 + y3 level: 2 fb =~ y1 + y2 + y3
In general, the first block describes the within level, and the second
block describes the between level. The blocks may be given in any order
if the labels reveal which level is which: if both labels are numbers, the
smallest number refers to the within level; the labels within and
between (in lower or upper case) are recognized, and so is a label
that equals the name of the cluster variable (the between level). In all
other cases (for example level: student and level: school,
if the cluster variable has a different name), the order of appearance is
used. In a multiple group model, the level blocks are nested within the
group: blocks.
Random slopes (two-level models)
In a two-level model (with a cluster= argument), the rv()
modifier can be used in the level-1 (within) part of the model to turn a
regression coefficient into a random slope: a latent variable at
the second (between) level. The (quoted) argument of rv() is the
name of this latent variable. At the between level, the random slope can
then be given a (residual) variance, covariances, regressions on
between-level covariates, and an intercept (which is the ‘fixed effect’
of the slope). For example (cfr. ex9.8 in the Mplus User's Guide):
model <- '
level: 1
fw =~ y1 + y2 + y3 + y4
fw ~ rv("s1")*x1 + rv("s2")*x2
level: 2
fb =~ y1 + y2 + y3 + y4
s1 + s2 + fb ~ w
'
Here, the within-level regression coefficients of fw on the
observed covariates x1 and x2 vary across clusters; the
random slopes s1 and s2 are regressed on the between-level
covariate w.
By default (in the sem(), cfa() and growth()
functions, or if auto_cov_rv = TRUE), a random slope is allowed
to covary with every other random effect of the between level:
the other random slopes;
the random intercepts: the between-level part of every observed variable that is also modeled at the within level (but not the exogenous covariates);
if such a variable is an indicator of a between-level factor, the factor takes the place of the random intercept: the random slope covaries with the factor, and not with the residual of the indicator.
No covariance is added if one of the two variables is regressed
(directly or indirectly) on the other, or if the variance of one of them
is fixed to zero. If one of them (or both) is a dependent variable, the
covariance is a residual covariance. In the example above, the
(residual) covariances between s1, s2 and fb are
therefore free parameters. As usual, a covariance can be fixed to zero
in the model syntax (s1 ~~ 0*s2), and all of them are removed by
setting auto_cov_rv = FALSE (or orthogonal = TRUE).
Why are they free by default? A model where the covariance between a
random intercept and a random slope is fixed to zero is not invariant to
the location of the covariate: if a constant is added to the covariate
(for example, if it is centered), this covariance changes, and a
different model is fitted (with a different loglikelihood, and a
different variance for the random slope). The results should not depend
on an arbitrary choice of origin, unless this is what the user asks for.
In addition, the random slopes are exogenous latent variables at the
between level, and exogenous latent variables are correlated by default
in the sem() and cfa() functions. Many (but not all)
programs for mixed models also estimate these covariances by default.
Mplus does not: the random effects are uncorrelated unless the
covariances are added explicitly, and this is also what lavaan does if
mimic = "Mplus". Note that the number of covariances increases
quickly with the number of random slopes, and that solutions on the
boundary (a singular covariance matrix of the random effects) are more
likely; if this happens, consider fixing some covariances to zero.
The covariate that carries a random slope may also be a latent (within-level) variable, as in
model <- '
level: 1
fxw =~ x1 + x2 + x3
fyw =~ y1 + y2 + y3
fyw ~ rv("s1")*fxw
level: 2
fxb =~ x1 + x2 + x3
fyb =~ y1 + y2 + y3
fyb ~ fxb
fyb ~~ s1
'
Such a slope multiplies two random variables, and the marginal
loglikelihood is no longer available in closed form: it is computed by
(Gauss-Hermite) quadrature over the latent-covariate slopes only,
while all other random effects are still integrated out analytically
(Rockwood, 2020). The number of quadrature points (per dimension) can
be set via the integration_ngh option (default: 21).
The same route is taken when the covariate is a ‘split’ both-level observed variable (an observed variable that appears in both the level-1 and the level-2 part of the model): the random slope then multiplies its latent within-cluster component (latent centering), and the covariate is jointly modeled:
model <- '
level: 1
y ~ rv("s1")*x
level: 2
y ~ x
y ~~ s1
'
This is the latent-covariate contextual model of Rockwood (2020, section 4). Note the contrast with a within-only covariate (a variable that does not appear in the level-2 part): there, the slope multiplies the observed values, which are conditioned upon.
The current implementation is limited to: two-level models, a single
group, continuous data, estimator = "ML" and fixed_x =
TRUE; the observed covariates that carry a random slope must be
within-only (level-1) variables. Missing data can be handled by
full-information maximum likelihood (missing = "ml"); the
exogenous covariates themselves must be complete (cases with missing
values on exogenous variables are removed). The (observed-data)
loglikelihood is conditional on all exogenous
covariates: the covariates carrying random slopes, any other
within-only exogenous covariates (as in Mplus
TYPE = TWOLEVEL RANDOM), and the between-level exogenous
covariates. Between-only endogenous observed variables
(level-2 outcomes, e.g., indicators of a between-level factor) are
supported; they must be pure indicators (not involved in
regressions), with a free (or fixed to a nonzero value) residual
variance. They may contain missing values (missing = "ml"):
the clusters with missing values are retained. To use a level-2
variable with missing values as a predictor (or as an outcome in a
regression), define a between-level latent variable with this variable
as its single indicator, and fix the residual variance of the
indicator to a small value:
level: 2
zb =~ 1*z
z ~~ 0.001*z
zb ~ w
s1 ~ zb
Similarly, a level-1 covariate with missing values can carry a random
slope if it is brought into the model as the single indicator of a
within-level latent variable (xw =~ 1*x; x ~~ 0*x), so that the
latent-covariate route described above is taken (the cases with a
missing value on this covariate are then retained, as in Mplus when
the variance of the covariate is mentioned in the model). No
chi-square test statistic (or fit indices) are available for models
with random slopes; fitMeasures() provides the
loglikelihood-based measures only (npar, ntotal,
logl, aic, bic, bic2), plus (with
estimator = "MLR") the H0 scaling correction factor
(scaling.factor.h0), which can be used for scaled
(loglikelihood) difference tests. Standard errors can be
"standard" (observed
information) or "robust.huber.white" (sandwich; this is also
what estimator = "MLR" implies). Both optim_method =
"nlminb" and optim_method = "em" are supported; with complete
data, "nlminb" is the default, while with missing =
"ml", the EM algorithm is the default optimizer.
lavPredict() provides empirical Bayes (posterior mean)
predictions: with level = 2, the
between-level latent variables including the random slopes (and, with
se = "standard", their posterior standard deviations); with
level = 1 (the default), the within-level factor scores. For
latent-covariate models, these are EAP (expected a posteriori)
estimates: the posterior is a mixture over the quadrature nodes.
For random slopes with latent covariates, some additional restrictions
apply (for now): a random-slope label may not be attached to both an
observed and a latent covariate, and the optimizer is always
"nlminb". The latent-covariate slopes may be regressed on
between-level covariates (e.g., s1 ~ w in the level-2 part),
as in the PISA example of Rockwood (2020).
(In)equality constraints
The == operator can be used either to fix a parameter to a specific value,
or to set an estimated parameter equal to another parameter. Adapting the
example in the Parameter labels and equality constraints section, we
could have used different labels for the second factor's intercepts:
y2a ~ int1*1
y2b ~ int2*1
y2c ~ int3*1
Then, we could fix the first intercept to zero by including in the syntax an operation that indicates the parameter's label equals that value:
int1 == 0
Whereas we could still estimate the other two intercepts under an equality constraint by setting their different labels equal to each other:
int2 == int3
Optimization can be less efficient when constraining parameters this way (see
the documentation linked under See also for more information). But the
flexibility might be advantageous. For example, the constraints could be
specified in a separate character-string object, which can be passed to the
lavaan(..., constraints=) argument, enabling users to compare results
with(out) the constraints.
Inequality constraints work in much the same way, using the < or >
operator to indicate which estimated parameter is hypothesized to be greater or
less than either a specific value or another estimated parameter. For example, a
variance can be constrained to be nonnegative:
y1a ~~ var1a*y1a
## hypothesized constraint:
var1a > 0
Or the factor loading of a particular indicator might be expected to exceed other indicators' loadings:
f1 =~ L1*y1a + L2*y1b + L3*y1c
## hypothesized constraints:
L1 > L2
L3 < L1
User-defined parameters
Functions of parameters can be useful to test particular hypotheses. Following
from the Multiple groups example, we might be interested in which group's
factor loading is larger (i.e., an estimate of differential item functioning
(DIF) when the latent scales are linked by anchor items with equal loadings).
speed =~ c(L7, L7)*x7 + c(L8, L8)*x8 + c(L9.group1, L9.group2)*x9 ' ## user-defined parameter: DIF_L9 := L9.group1 - L9.group2
Note that this hypothesis is easily tested without a user-defined parameter by
using the lavTestWald() function. However, a user-defined parameter
additionally provides an estimate of the parameter being tested.
User-defined parameters are particularly useful for specifying indirect effects in models of mediation. For example:
model <- ' # direct effect
Y ~ c*X
# mediator
M ~ a*X
Y ~ b*M
# user defined parameters:
# indirect effect (a*b)
ab := a*b
# total effect (defined using another user-defined parameter)
total := ab + c
'
Data-defined (moderated) parameters
The ":~" operator redefines an existing (labeled) free parameter as
a per-observation function of new component parameters and one or more
observed variables (often called ‘definition variables’). Every
observed variable in the right-hand side expression must be wrapped in
data(). For example, to let a factor loading vary linearly with a
moderator z:
model <- ' f =~ y1 + L2*y2 + y3
L2 :~ L2_0 + L2_1 * data(z) '
Here, the loading L2 is no longer a single free parameter: it is
replaced (for each observation) by the value of the expression, and two
new (free) component parameters (L2_0 and L2_1) are added
to the parameter table. The right-hand side may be any valid R
expression, and may also refer to other (free) parameter labels, or to
other ":~" definitions. For example, a factor covariance that is
moderated on the Fisher-z scale (bounding the corresponding correlation),
referring to the (labeled) factor variances:
model <- ' f1 ~~ psi_21*f2
f1 ~~ psi_11*f1
f2 ~~ psi_22*f2
psi_21 :~ tanh(zr_0 + zr_1 * data(z)) * sqrt(psi_11*psi_22) '
A definition may also depend on the data only indirectly, through
another ":~" definition (‘chained’ definitions). For
example, if the slope b1 is moderated by z, a second slope
can be defined as a function of b1:
model <- ' y1 ~ b1*x
y2 ~ b2*x
b1 :~ a0 + a1 * data(z)
b2 :~ 0.5 * b1 + c0 '
A definition that involves neither a data() reference nor another
":~" definition is refused: a parameter that is a function of
other parameters only is defined using ":=" (or an equality
constraint).
While the ":=" operator defines a new parameter as a function of
other parameters only, a ":~" definition involves the data, and
therefore changes the model itself: estimation requires a casewise
likelihood. lavaan itself can not (yet) estimate such models; calling
lavaan() (or sem(), cfa(), ...) with
do_fit = FALSE returns an (unfitted) object holding the complete
model specification (parameter table, starting values, and the
dv.function in the @Model slot) that external packages can
use to estimate the model with a suitable backend; alternatively, a
registered backend (see lavBackendRegister) can be named
in the backend argument, in which case lavaan calls it and
returns a fitted object (see lavImportResults). Because a
casewise
likelihood always involves the means, models with ":~"
definitions always have a mean structure (meanstructure = TRUE
is forced). Cases with a missing value for a definition variable can
not contribute to the likelihood, and are always removed (whatever the
value of the missing argument); a warning is given unless
missing = "listwise". A definition variable that is also an
endogenous (dependent) variable in the model triggers a warning: the
definition conditions on its observed values, while the model also
describes it. The parameter table of the ‘unmoderated’ model (the
model without the ":~" definitions, with the moderated parameters
free again) is returned by lavInspect(fit, "list_unmoderated");
backends can use it, for example, to obtain warm starts or a reference
model.
Because the model-implied moments vary across observations, everything
that is derived from a single moment structure is refused for these
models, rather than being evaluated at the representative starting values
of the moderated cells: fitted(), residuals(),
modindices(), lavTestScore(),
standardizedSolution(), lavPredict(), bootstrapping, and
the corresponding lavInspect() keywords; the test option
is set to "none" and no baseline model is fitted. Once a backend
has supplied the casewise log-likelihood, logLik(), AIC(),
BIC(), the log-likelihood based fitMeasures() (logl,
aic, bic, bic2, npar, ntotal) and
lavTestLRT() between nested models of this class are available,
and se = "bootstrap" (or lavBootstrap()) re-estimates
every resampled data set through the backend; without it, logLik()
returns NA with a warning. The
parameter estimates, standard errors, and coef()/vcov()
are always available.
Note the difference with random slopes (the rv() modifier): a
random slope varies across clusters as a latent variable, while a
data-defined parameter varies deterministically with observed variables.
References
Rockwood, N. J. (2020). Maximum likelihood estimation of multilevel structural equation models with random slopes for latent covariates. Psychometrika, 85(2), 275–300. doi:10.1007/s11336-020-09702-9
Rosseel, Y. (2012). lavaan: An R package for structural equation
modeling. Journal of Statistical Software, 48(2), 1–36.
doi:10.18637/jss.v048.i02
Modification Indices
Description
Given a fitted lavaan object, compute the modification indices (= univariate score tests) for a selected set of fixed-to-zero parameters.
Usage
modificationIndices(object, standardized = TRUE, cov_std = TRUE,
information = "expected",
power = FALSE, delta = 0.1, delta_std = FALSE,
alpha = 0.05,
high_power = 0.75, sort = FALSE, minimum_value = 0,
maximum_number = nrow(list_1), free_remove = TRUE,
na_remove = TRUE, op = NULL, ...)
modindices(object, standardized = TRUE, cov_std = TRUE, information = "expected",
power = FALSE, delta = 0.1, delta_std = FALSE,
alpha = 0.05, high_power = 0.75,
sort = FALSE, minimum_value = 0,
maximum_number = nrow(list_1), free_remove = TRUE,
na_remove = TRUE, op = NULL, ...)
Arguments
object |
An object of class |
standardized |
If |
cov_std |
Logical. See |
information |
|
power |
If |
delta |
The value of the effect size, as used in the post-hoc power
computation. Per default ( |
delta_std |
Logical or character. If |
alpha |
The significance level used for deciding if the modification
index is statistically significant or not. The decision is based on the
|
high_power |
If the computed power is higher than this cutoff value, the power is considered ‘high’. If not, the power is considered ‘low’. This affects the values in the 'decision' column in the output. |
sort |
Logical. If TRUE, sort the output by the modification index values. Higher values appear first. |
minimum_value |
Numeric. Filter output and only show rows with a modification index value equal to or higher than this minimum value. |
maximum_number |
Integer. Filter output and only show the first
|
free_remove |
Logical. If TRUE, filter output by removing all rows corresponding to free (unconstrained) parameters in the original model. |
na_remove |
Logical. If TRUE, filter output by removing all rows with NA values for the modification indices. |
op |
Character string. Filter the output by selecting only those rows with
operator |
... |
To support old argument names. |
Details
Modification indices are just 1-df (or univariate) score tests. The modification index (or score test) for a single parameter reflects (approximately) the improvement in model fit (in terms of the chi-square test statistic) if we were to refit the model with this parameter set free.
The standard modification index (the mi column) is the score test
based on the expected information matrix. It follows a chi-square
distribution with one degree of freedom only if the estimator is
asymptotically efficient and the distributional assumptions hold: for
example for maximum likelihood with (multivariate) normal data, or for
estimator = "WLS". For estimators that are not asymptotically
efficient ("DWLS", "ULS", and therefore also
"WLSMV", "ULSMV" and their relatives), and for
"ML" with non-normal data, the standard index is not chi-square
distributed, its expected value under the null hypothesis may be larger
or smaller than one, and even the ranking of the candidate parameters
can be affected. Whenever the fitted object provides the ingredients for
a sandwich (robust) covariance matrix (robust standard errors, or a
scaled test statistic, as for "MLM", "MLR",
"WLSMV", "ULSMV"), an extra column mi.scaled is
added with the scaled version of the score test (Satorra, 2000), which
for a single parameter coincides with the generalized (robust) version.
This column is identical to the X2.scaled column of the
univariate table of lavTestScore (and to the
score.robust statistic of lavTestScore(add = )), but it
is computed for all candidate parameters at once. The mi.scaled
column should be used to judge the significance of a candidate parameter
(the power option does so automatically); the mi column
is kept for comparability with other software. The expected parameter
change (epc) values do not depend on this choice.
This function is a convenience function in the sense that it produces a
(hopefully sensible) table of currently fixed-to-zero (or fixed to another
constant) parameters. For each of these parameters, a modification index
is computed, together with an expected parameter change (epc) value.
It is important to realize that this function will only consider
fixed-to-zero parameters. If you have equality constraints in the model,
and you wish to examine what happens if you release all (or some) of these
equality constraints, use the lavTestScore function.
Value
A data.frame containing modification indices and EPCs. The mi
column holds the standard modification index; the mi.scaled
column (only present when the fitted object provides the ingredients for
a sandwich covariance matrix, see Details) holds its scaled (robust)
version.
References
Satorra, A. (2000). Scaled and adjusted restricted tests in multi-sample analysis of moment structures. In Heijmans, R.D.H., Pollock, D.S.G. & Satorra, A. (eds.), Innovations in multivariate statistical analysis. A Festschrift for Heinz Neudecker (pp.233-247). London: Kluwer Academic Publishers.
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
modindices(fit, minimum_value = 10, sort = TRUE)
# robust standard errors: the mi.scaled column is added
fit2 <- cfa(HS.model, data=HolzingerSwineford1939, estimator = "MLM")
modindices(fit2, minimum_value = 10, sort = TRUE)
The open parser configuration
Description
The lavaan model syntax parser can be extended with new operators, modifiers and groupings. These extensions are only used in the 'open' parser.
Usage
lav_parse_options(
pkgname = NULL,
operators = NULL,
modifiers = NULL,
groupings = NULL
)
Arguments
pkgname |
The name of the package that extends the elements. |
operators |
A character vector with new operators. These operators must start and end with a percentage sign and be at least 3 characters long. |
modifiers |
A data.frame with columns |
groupings |
A character vector with new groupings; they must be in snake_case. |
Value
A list with data.frames containing the currently active parser configuration.
Examples
curconfig <- lav_parse_options("testPKG",
operators = c('%w%', '%q%'),
modifiers = data.frame(mod = c("linksc", "linksn", "rechtsn"),
side = c("l", "l", "r"),
expect = c("char", "num", "raw")),
groupings = c("color", "colour")
)
for (j in seq_along(curconfig)) {
cat(names(curconfig)[j], ":\n")
print(curconfig[[j]])
}
model <- '
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + a*y2 + start(0.3)*b*y3 + upper(0.99)*c*y4
dem65 =~ y5 + a*y6 + b*y7 + rechtsn(2 * pi / 3)*c*y8
dem60 %w% aa *0.2*y4
dem60 ~ ind60
dem65 ~ ind60 + dem60
linksc("klopt") * dem60 =~ aaa * y8
linksn(sqrt(23.5)) * dem60 =~ bbb * y9
efa("efatje") * dem65 =~ xyz * x3
y1 ~~ y5
y2 ~~ y4 + y6
y3 ~~ y7
y4 ~~ y8
y6 ~~ y8
'
print(result <- lavParseModelString(model, TRUE, parser = "open"))
print(attributes(result))
model2 <- '
color: green
level: 1
fw =~ y1 + y2 + y3
fw ~ x1 + x2 + x3
level: 2
fb =~ y1 + y2 + y3
fb ~ w1 + w2
color: blue
level: 1
fw =~ y1 + y2 + y3
fw ~ x1 + x2 + x3
level: 2
fb =~ y1 + y2 + y3
fb ~ w1 + w2
'
print(result2 <- lavParseModelString(model2, TRUE, parser = "open"))
print(attributes(result2))
Parameter Table
Description
Show the parameter table of a fitted model.
Usage
parameterTable(object)
parTable(object)
Arguments
object |
An object of class |
Value
A data.frame containing the model parameters. This is
simply the output of the lavParTable function
coerced to a data.frame (with stringsAsFactors = FALSE).
See Also
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
parTable(fit)
Fit Structural Equation Models using the SAM approach
Description
Fit a Structural Equation Model (SEM) using the Structural After Measurement (SAM) approach.
Usage
sam(model = NULL, data = NULL, aux = NULL, cmd = "sem", se = "default",
mm_list = NULL, mm_args = list(bounds = "wide.zerovar"),
struc_args = list(estimator = "ML"),
sam_method = "local", ...,
local_options = list(m_method = "ML", lambda_correction = TRUE,
lambda1_floor = "debias", lambda2_floor = "debias",
alpha_correction = 0L, twolevel_method = "h1",
gamma_eta = "casewise", bias_correction = "none"),
global_options = list(),
bootstrap = list(R = 1000L, type = "ordinary", show_progress = FALSE),
output = "lavaan",
bootstrap_args = bootstrap
)
Arguments
model |
A description of the user-specified model. Typically, the model
is described using the lavaan model syntax. See
|
data |
A data frame containing the observed variables used in the model. |
aux |
Character vector. Names of auxiliary observed variables, forwarded
to the underlying measurement and structural model fits. See the
|
cmd |
Character. Which command is used to run the sem models. The possible
choices are |
se |
Character. The type of standard errors that are used in the
final (structural) model. If |
mm_list |
List. Define the measurement blocks.
Each element of the list should
be either a single name of a latent variable, or a vector of latent
variable names. If omitted, a separate measurement
block is used for each latent variable. Composites (defined by the
|
mm_args |
List. Optional arguments for the fitting
function(s) of the measurement block(s) only. See |
struc_args |
List. Optional arguments for the fitting function of the
structural part only. See |
sam_method |
Character. Can be set to |
... |
Many more options can be specified, using 'name = value'.
See |
local_options |
List. Options specific for local SAM method (these
options may change over time; both the dot.case and the snake_case
spelling of the element names are accepted, e.g.,
|
global_options |
List. Options specific for global SAM method (not used for now). |
bootstrap |
List. Only used when |
output |
Character. If |
bootstrap_args |
List. Deprecated, use |
Details
The sam function automates the SAM approach by first
estimating the measurement part of the model and then the structural
part of the model. See the reference for more details.
Note that in the current implementation, all indicators of latent variables must be observed. As a result, second-order factor structures are not yet supported.
If sam_method is "local", "fsr" or "cfsr",
the structural part of the model is fitted to the estimated latent
(co)variances (and means) from step 1. This step-2 structural model is
stored in the @internal slot of the returned object, and can be
retrieved by lavInspect(fit, "sam.struc.fit.object"). The
functions fitMeasures (and
summary(fit, fit_measures = TRUE)), lavResiduals
(and summary(fit, residuals = TRUE)), modindices
and lavTestLRT (when all compared models are local SAM
models) operate on this structural model: the reported quantities
describe the fit of the structural part only, conditional on the (fixed)
measurement model of step 1. When available, the reported (scaled) test
statistic and the robust fit measures are corrected for the estimation
of the measurement model in step 1: by default, this is the
Satorra-Bentler scaled structural test, driven by the asymptotic
covariance matrix of the latent moments (which accounts for step 1).
The test argument may request another member of the
Satorra-Bentler family for the structural test instead:
"mean.var.adjusted", "scaled.shifted", or their
"corrected" versions "mean.var.adjusted.corrected" and
"scaled.shifted.corrected" (see lavTest), which
use the unbiased estimator of the second-order trace of Hayakawa
(2018), computed from the casewise contributions of the observations
to the latent moments (available for single-group, single-level models
with continuous indicators, except with se = "local.nt"; in
other settings the corrected tests are dropped with a warning).
Several tests can be combined, for instance
test = c("satorra.bentler", "mean.var.adjusted.corrected").
The structural model contains all latent variables of the model (not
only the ones that appear in a regression), together with the observed
variables that appear in a regression: the variances of the latent
variables, and their covariances, are structural parameters, estimated
in step 2 (in a higher-order model, the lower-order factors belong to
the measurement part, unless they appear in a regression themselves).
The measurement blocks of step 1 inherit the test argument as
well (unless overridden in mm_args): when a scaled test is
requested, the block table in the summary shows that (first) scaled
test statistic (columns Chisq.scaled and Df.scaled),
otherwise the standard chi-square statistic.
With one factor per measurement block (the default mm_list), the
blockwise estimation of the loadings and residual variances in step 1
induces a small-sample bias in the estimated latent correlations: they
are attenuated (pulled towards zero) by a factor of approximately
1 - [(1 - \rho^2)/2 + h_k + h_l]/(N - 1), where the block terms
h_k and h_l depend only on the noise-to-signal ratios
\theta_i/\lambda_i^2 of the indicators of the two factors: they
vanish for reliable indicators, grow quadratically in the noise-to-signal
ratio, and decrease roughly in proportion to the number of indicators
per factor. For example, with three indicators per factor, standardized
loadings of 0.5 and a true correlation of 0.6, the predicted attenuation
is about -0.13 when N = 100 and -0.03 when N = 400; with
standardized loadings of 0.7 it is -0.03 and -0.01. After step 1,
sam() computes this prediction (stabilized as in the analytic
plug-in correction: noise-to-signal ratios winsorized at three times the
pooled ratio of their block, relative attenuation capped at 50 percent)
for every pair of factors that are measured by separate congeneric
blocks of at least three indicators, when the data are continuous,
complete and single-level, the measurement blocks are estimated by ML
without equality constraints, and the ML mapping is used. The
summary() lists the latent correlations whose predicted bias is
at least 0.05 in absolute value; the full results are available through
lavInspect(fit, "sam_attenuation"). By default the estimates
are not corrected; the local option bias_correction = "plugin"
applies the analytic plug-in correction (the attenuation factor is
estimated from the step-1 estimates and divided out of the latent
correlations; in simulations this removes most of the attenuation for
N \ge 100, at an RMSE cost of at most a few percent, and does
better than a bootstrap bias correction in both bias and RMSE).
The bias is absent when all factors are placed in a single
measurement block (e.g., mm_list = list(c("f1", "f2", "f3"))):
the latent covariance matrix then equals the (bounded) joint ML
estimate, which keeps the robustness of SAM against a misspecified
structural model, but gives up the protection against measurement
misspecification in other blocks. Merging only the weakly measured
factors into a common block, or using more indicators per factor, are
intermediate options.
If sam.method is "global", the returned object is an
ordinary (joint) lavaan object, and fitMeasures returns the usual
fit measures of the joint model. Note, however, that the parameters were
estimated using a two-step procedure; the behavior of fit measures in
this setting has not been studied, and they should be interpreted with
caution.
Value
If output = "lavaan", an object of class
lavaan, for which several methods
are available, including a summary method. If output = "list",
a list.
Exogenous covariates and conditional_x
Observed exogenous covariates may enter the structural part of the
model. With continuous data, they are simply treated as (pseudo) latent
variables (the default conditional_x = FALSE), but
conditional_x = TRUE is supported as well (single-group,
single-level models): the structural part is then fitted to the latent
intercepts, the latent-on-covariate slopes, and the residual latent
(co)variances, all conditional on the covariates.
With categorical (ordered) data, conditional_x = TRUE is the
lavaan default (when exogenous covariates are present), and this is also
the recommended setting: the covariates are conditioned on (as in a
probit regression), rather than being absorbed into the joint polychoric
correlation matrix – which would (wrongly) treat them as jointly normal,
a real concern for binary/dummy covariates. In this setting, the
measurement blocks of step 1 are estimated with
conditional_x = TRUE as well (each block latent variable is
regressed on all exogenous covariates, MIMIC style), so that the
measurement parameters live on the same conditional latent-response
scale (Var(y*|x) = 1, Delta parameterization) as the joint model.
An ordered endogenous variable in the structural part is
supported too (with or without covariates): it enters the structural
model on its latent-response scale, while its thresholds are fixed at
their sample-based values.
When conditional_x = TRUE is combined with a local
sam.method, se = "twostep" is automatically
replaced by se = "twostep.robust": the classic two-step formula is
built on the joint information matrix, which does not describe the local
step-2 estimator in this setting (it underestimates the sampling
variability, especially for binary covariates). The robust variant is
computed as a structural-space sandwich here, and coincides with
se = "local".
When latent interactions are combined with missing = "ml" (local
sam.method), the factor scores that feed the second-order
(interaction) moments are computed per missing-data pattern, using
pattern-specific mapping matrices and measurement-error covariances.
The first-order moments are based on the EM (h1) statistics and remain
consistent under MAR; the second-order (interaction) layer is
moment-based, and is consistent under MCAR. Cases for which some factor
has no observed indicators cannot be scored: they are excluded from the
interaction moments (with a warning), although they still contribute to
the first-order moments.
Not (yet) available in combination with conditional_x = TRUE:
multiple groups (for the local standard errors and the corrected test
statistic), multilevel models, latent interactions, and the Yuan-Chan
scaled global test statistic of sam_method = "global" (the
standard, unscaled test is reported instead, with a warning).
References
Rosseel and Loh (2021). A structural-after-measurement approach to Structural Equation Modeling. Psychological Methods. Advance online publication. https://dx.doi.org/10.1037/met0000503
See Also
Examples
## The industrialization and Political Democracy Example
## Bollen (1989), page 332
model <- '
# latent variable definitions
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + a*y2 + b*y3 + c*y4
dem65 =~ y5 + a*y6 + b*y7 + c*y8
# regressions
dem60 ~ ind60
dem65 ~ ind60 + dem60
# residual correlations
y1 ~~ y5
y2 ~~ y4 + y6
y3 ~~ y7
y4 ~~ y8
y6 ~~ y8
'
fit.sam <- sam(model, data = PoliticalDemocracy,
mm.list = list(ind = "ind60", dem = c("dem60", "dem65")))
summary(fit.sam)
Fit Structural Equation Models
Description
Fit a Structural Equation Model (SEM).
Usage
sem(model = NULL, data = NULL, ordered = NULL, aux = NULL, sampling_weights = NULL,
sample_cov = NULL, sample_mean = NULL, sample_th = NULL,
sample_nobs = NULL, group = NULL, cluster = NULL, panel = NULL,
constraints = "", wls_v = NULL, nacov = NULL, ov_order = "model",
sampling_weights_cluster = NULL, ...)
Arguments
model |
A description of the user-specified model. Typically, the model
is described using the lavaan model syntax. See
|
data |
An optional data frame containing the observed variables used in the model. If some variables are declared as ordered factors, lavaan will treat them as ordinal variables. |
ordered |
Character vector. Only used if the data is in a data.frame. Treat these variables as ordered (ordinal) variables, if they are endogenous in the model. Importantly, all other variables will be treated as numeric (unless they are declared as ordered in the data.frame.) Since 0.6-4, ordered can also be logical. If TRUE, all observed endogenous variables are treated as ordered (ordinal). If FALSE, all observed endogenous variables are considered to be numeric (again, unless they are declared as ordered in the data.frame.) |
aux |
Character vector. Names of auxiliary observed variables, used to
make the missing-at-random (MAR) assumption more plausible under missing
data (continuous data only). With |
sampling_weights |
A variable name in the data frame containing
sampling weight information. Depending on the
|
sample_cov |
Numeric matrix. A sample variance-covariance matrix. The rownames and/or colnames must contain the observed variable names. For a multiple group analysis, a list with a variance-covariance matrix for each group. |
sample_mean |
A sample mean vector. For a multiple group analysis, a list with a mean vector for each group. |
sample_th |
Vector of sample-based thresholds. For a multiple group analysis, a list with a vector of thresholds for each group. |
sample_nobs |
Number of observations if the full data frame is missing and only sample moments are given. For a multiple group analysis, a list or a vector with the number of observations for each group. |
group |
Character. A variable name in the data frame defining the groups in a multiple group analysis. |
cluster |
Character. A (single) variable name in the data frame defining the clusters in a two-level dataset. |
panel |
Character. If the data are long panel data (one row per
person and occasion), the names of the id and the time variable, as in
|
constraints |
Additional (in)equality constraints not yet included in the
model syntax. See |
wls_v |
A user provided weight matrix to be used by estimator |
nacov |
A user provided matrix containing the elements of (N times)
the asymptotic variance-covariance matrix of the sample statistics.
For a multiple group analysis, a list with an asymptotic
variance-covariance matrix for each group. See the |
ov_order |
Character. If |
sampling_weights_cluster |
A variable name in the data frame containing
the sampling weights of the clusters (level-2 units). Only used for
two-level models (see the |
... |
Many more options can be specified, using 'name = value'.
See |
Details
The sem function is a wrapper for the more general
lavaan function, using the following default arguments:
int_ov_free = TRUE, int_lv_free = FALSE,
auto_fix_first = TRUE (unless std_lv = TRUE),
auto_fix_single = TRUE, auto_var = TRUE,
auto_cov_lv_x = TRUE, auto_efa = TRUE,
auto_th = TRUE, auto_delta = TRUE,
auto_cov_y = TRUE, and auto_cov_rv = TRUE (unless
mimic = "Mplus").
Value
An object of class lavaan, for which several methods
are available, including a summary method.
References
Yves Rosseel (2012). lavaan: An R Package for Structural Equation Modeling. Journal of Statistical Software, 48(2), 1-36. doi:10.18637/jss.v048.i02
See Also
lavaan, estimator_iv, estimator_js
Examples
## The industrialization and Political Democracy Example
## Bollen (1989), page 332
model <- '
# latent variable definitions
ind60 =~ x1 + x2 + x3
dem60 =~ y1 + a*y2 + b*y3 + c*y4
dem65 =~ y5 + a*y6 + b*y7 + c*y8
# regressions
dem60 ~ ind60
dem65 ~ ind60 + dem60
# residual correlations
y1 ~~ y5
y2 ~~ y4 + y6
y3 ~~ y7
y4 ~~ y8
y6 ~~ y8
'
fit <- sem(model, data = PoliticalDemocracy)
summary(fit, fit_measures = TRUE)
Standardized Solution
Description
Standardized solution of a latent variable model.
Usage
standardizedSolution(object, type = "std_all", se = TRUE, zstat = TRUE,
pvalue = TRUE, ci = TRUE, level = 0.95,
boot_ci_type = "perc", cov_std = TRUE,
remove_eq = TRUE, remove_ineq = TRUE, remove_def = FALSE,
remove_aux = TRUE,
partable = NULL, glist = NULL, est = NULL,
output = "data.frame", ...)
Arguments
object |
An object of class |
type |
Character (dots and underscores are interchangeable:
|
se |
Logical. If TRUE, standard errors for the standardized parameters will be computed, together with a z-statistic and a p-value. |
zstat |
Logical. If |
pvalue |
Logical. If |
ci |
If |
level |
The confidence level required. |
boot_ci_type |
Character. Only used if the model was fitted with
|
cov_std |
Logical. If TRUE, the (residual) observed covariances are scaled by the square root of the ‘Theta’ diagonal elements, and the (residual) latent covariances are scaled by the square root of the ‘Psi’ diagonal elements. If FALSE, the (residual) observed covariances are scaled by the square root of the diagonal elements of the observed model-implied covariance matrix (Sigma), and the (residual) latent covariances are scaled by the square root of diagonal elements of the model-implied covariance matrix of the latent variables. |
remove_eq |
Logical. If TRUE, filter the output by removing all rows containing equality constraints, if any. |
remove_ineq |
Logical. If TRUE, filter the output by removing all rows containing inequality constraints, if any. |
remove_def |
Logical. If TRUE, filter the output by removing all rows containing parameter definitions, if any. |
remove_aux |
Logical. If TRUE (the default), filter the output by
removing all rows corresponding to auxiliary ( |
glist |
List of model matrices. If provided, they will be used
instead of the GLIST inside the object@Model slot. Only works if the
|
est |
Numeric. Parameter values (as in the ‘est’ column of a
parameter table). If provided, they will be used instead of
the parameters that can be extracted from object. Only works if the |
partable |
A custom |
output |
Character. If |
... |
To support old argument names. |
Details
When the model contains product terms (interaction or quadratic terms,
written with a colon in the model syntax), the standardized solution treats
a product term with only latent components as the product of the centered,
standardized components: the product term is scaled by the product of the
standard deviations of its components (not by its own standard deviation),
the main effects of the components are reported as simple slopes evaluated
at the means of the other components, and the (co)variances and means
involving the product term are centered first. Product terms with an
observed component (x1:x2, f1:x1) follow the
std_ov_interaction option (see lavOptions): with the
default "component" they receive the same treatment as latent
product terms; with "product" (the behavior of lavaan versions
before 0.7-3) they are treated as variables in their own right (scaled by
their own standard deviation).
The standardized estimates are functions of the (unstandardized) free
parameters and of (a subset of) the model-implied (co)variances used for
scaling. The standard errors reported by standardizedSolution are
therefore standard errors for the standardized parameters, and they
will in general differ from the standard errors of the unstandardized
parameters reported by parameterEstimates (or in the
summary() output). They are also not the same as the standard errors
that would be obtained by simply rescaling the unstandardized standard errors.
How the standard errors are computed depends on how the model was originally
fitted (in particular on the se= argument of lavaan,
cfa, sem, ...):
By default (
se = "standard","robust.sem","robust.huber.white", ...), the standard errors are obtained with the delta method: the Jacobian of the standardization function is computed (numerically) and combined with the variance-covariance matrix of the (unstandardized) parameter estimates. Any robustness present in that variance-covariance matrix (for example robust or sandwich-type standard errors) is automatically propagated to the standardized solution.If the model was fitted with
se = "bootstrap"(and the bootstrap draws are available), bootstrap standard errors and bootstrap confidence intervals are reported instead. These are obtained by re-standardizing each bootstrap draw and computing the standard deviation (for the standard error) and the requested interval type (seeboot_ci_type) of the resulting standardized values. Note that, as inparameterEstimates, the p-value is still computed by referring the z-statistic (standardized estimate divided by its bootstrap standard error) to a standard normal distribution.
There is no separate argument to choose the type of standard error
within standardizedSolution: the type always follows the se=
setting that was used when the model was fitted. To obtain, say, robust or
bootstrap standard errors for the standardized solution, refit the model with
the corresponding se= argument.
Value
A data.frame containing standardized model parameters.
If the model was fitted with se = "bootstrap" (and the bootstrap
draws are available), the standardized estimates in the bootstrap samples
are stored as the "boot_std" attribute of the returned data.frame (a
matrix with one row per bootstrap draw and one column per row of the
returned solution). These can be retrieved with
attr(x, "boot_std"), analogous to
lavInspect(object, "coef_boot") for the unstandardized solution.
In addition, if boot_ci_type = "bca", the empirical-influence design
matrix used to compute the acceleration constant is stored as the
"design" attribute (retrieve with attr(x, "design")); see
parameterEstimates for the cases where the acceleration
constant is computed from the infinitesimal jackknife influence values
instead.
Note
The est, glist, and partable arguments are not meant for
everyday users, but for authors of external R packages that depend on
lavaan. Only to be used with great caution.
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
standardizedSolution(fit)
Variable Table
Description
Summary information about the variables included in either a data.frame, or a fitted lavaan object.
Usage
varTable(object, ov_names = names(object), ov_names_x = NULL,
ordered = NULL, factor = NULL, as_data_frame = TRUE, ...)
Arguments
object |
Either a data.frame, or an object of class
|
ov_names |
Only used if object is a data.frame. A character vector containing the variables that need to be summarized. |
ov_names_x |
Only used if object is a data.frame. A character vector containing additional variables that need to be summarized. |
ordered |
Character vector. Which variables should be treated as ordered factors? |
factor |
Character vector. Which variables should be treated as (unordered) factors? |
as_data_frame |
If TRUE, return the list as a data.frame. |
... |
To support old argument names. |
Value
A list or data.frame containing summary information about
variables in a data.frame. If object is a fitted lavaan object,
it displays the summary information about the observed variables that are
included in the model. The summary information includes
variable type (numeric, ordered, ...), the number of non-missing values,
the mean and variance for numeric variables, the number of levels of
ordered variables, and the labels for ordered variables.
Examples
HS.model <- ' visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9 '
fit <- cfa(HS.model, data=HolzingerSwineford1939)
varTable(fit)