model <- '
visual =~ x1 + x2 + x3
textual =~ x4 + x5 + x6
speed =~ x7 + x8 + x9
'
fit <- cfa(model, data = HolzingerSwineford1939)20 Epilogue
20.1 The pipeline, revisited
The introduction opened with a promise, in the form of a flowchart: that everything lavaan does can be understood as a pipeline leading from a character string and a data frame to a fitted object, and that this book would go through that pipeline box by box. At the end of the book, the promise can be fulfilled. Consider, one last time, the model that has accompanied us throughout:
The cfa() function, like sem() and growth(), is only a thin wrapper that fills in a set of default options and then calls the function that does the actual work, lavaan(). And the body of lavaan() reads, quite literally, like the table of contents of this book. The stages of the pipeline are not an artifact of the R code: they are the logical structure of fitting an SEM, and they will survive any reorganization of the source. Between the call above and the return of fit, the following happens:
Names, options, and data: the model syntax is parsed into a flat intermediate table, from which the names of the observed variables are extracted; the user options are resolved (every
"default"placeholder is replaced by an actual value, in a way that may depend on the data and the estimator); and the data are ingested into an internallavDataobject (Chapters 2 and 5).The parameter table:
lavaanify()expands the parsed syntax into the parameter table, the central data structure of the package (chapter 3), adding residual variances, latent (co)variances, and fixed marker loadings according to theauto_*options.Sample statistics and the \mathsf{H}_1 model: the sample moments \mathbf{S} and \bar{\mathbf{y}} are computed, along with the asymptotic covariance matrix \boldsymbol{\Gamma} of Section 5.6.2 when robust inference is requested, and the unrestricted (\mathsf{H}_1) model that serves as the reference point for the chi-square test (chapter 5).
Bounds and starting values: the parameter bounds of Section 6.2.2 are derived, and starting values are computed (chapter 6).
The model object: the parameter table is translated into the LISREL-style model matrices of Section 4.1, the representation on which all numerical work is based (chapter 4).
Optimization: the discrepancy function (Section 7.2) is minimized, by default with a quasi-Newton method using analytic gradients, and the convergence checks of Section 7.11 are applied (chapter 7).
Inference: the model-implied moments are stored, the requested variance–covariance matrix of the estimates is assembled from the information matrices and, if needed, a sandwich construction (Section 8.4), and the test statistics are computed (Section 8.5; chapter 8).
The baseline model: the independence model of Section 10.2.1 is fitted, so that incremental fit indices can be computed later (chapter 10).
Rotation: for models with EFA blocks, the rotation procedures of chapter 15 are applied to the estimates and their standard errors; for our CFA, this stage is skipped.
Assembly: everything is bundled into the S4
lavaanobject of chapter 9, whose contents can be inspected withlavInspect()(Section 9.12).
The fitted object also keeps a record of this: the timing information returned by lavInspect(fit, "timing") records how long each part of the computation took, and its element names retrace the pipeline one more time.
round(unlist(lavInspect(fit, "timing")), 3) start_time.elapsed init.elapsed ov.names.elapsed Options.elapsed
0.442 0.000 0.015 0.003
Data.elapsed ParTable.elapsed SampleStats.elapsed h1.elapsed
0.002 0.008 0.002 0.000
bounds.elapsed start.elapsed Model.elapsed cache.elapsed
0.001 0.001 0.004 0.000
optim.elapsed implied.elapsed loglik.elapsed vcov.elapsed
0.007 0.000 0.000 0.003
test.elapsed Fit.elapsed baseline.elapsed rotation.elapsed
0.002 0.000 0.011 0.000
total.elapsed
0.059
Much of the rest of the book concerns what follows this pipeline: fit measures (Section 10.2) and residuals (Section 10.8), modification indices (Section 10.11), the likelihood ratio, Wald and score tests of Section 11.1.2, the standardized solution (Section 12.1), and factor scores (Section 13.3). The remaining chapters are, in the end, variations on the same theme. A correlation structure (Section 12.5) replaces the sample covariance matrix by the sample correlation matrix, and adapts the model accordingly. Categorical data (Section 14.1) replace the sample moments by thresholds and polychoric correlations, and adjust the estimator. Multilevel models (Section 16.1) replace the log-likelihood by its two-level counterpart. EFA and ESEM (Section 15.1) activate the rotation stage. The multi-stage estimators (Section 17.1) replace the optimization stage by a sequence of non-iterative computations on the sample moments. SAM (Section 18.1) runs the pipeline several times over, once per measurement block and once more for the structural part. And a simulation study (Section 19.1) runs it thousands of times. A reader who has followed these chapters has not learned a series of separate procedures, but one procedure in many variations.
20.2 Extending lavaan
Among the readers we had in mind from the start are those who want to change what lavaan does: fix a bug, add a fit measure, or implement a methodological idea of their own, either inside lavaan itself or in a package of their own built on top of it. After the preceding chapters, the code base should no longer be intimidating. For contributions to lavaan proper, development takes place in the open: the source code is available in a public git repository, and the website https://lavaan.org tells where to find it. Bug reports and feature requests are best filed as issues in that repository, ideally with a small reproducible example.
Here, a word of encouragement drawn from recent experience: writing this book doubled as an audit of the code it describes. Checking every formula against the source uncovered a handful of genuine bugs, which were fixed during the writing of this book. The lesson generalizes. Reading source code with a critical eye is not an act of distrust; it is how scientific software gets better. If something in lavaan surprises you, trace it, with this book as a guide, and tell us what you find.
20.2.1 Building a package on top of lavaan
Many readers will not change lavaan itself, but will write a package that imports from it or depends on it. More than 200 packages on CRAN already do. For the developers of such packages, it helps to know what the release of a new version of lavaan involves. The CRAN policy is that a new version must not break existing packages. Before a new version can be submitted, all reverse dependencies are checked one by one: each package is installed, and its examples, unit tests and vignettes are run against the release candidate. For every package that breaks, the maintainer of lavaan must contact the maintainer of that package, explain what has changed, and wait until a repaired version has appeared on CRAN. A repair that takes ten minutes to write can take weeks or months to arrive. A typical update cycle of lavaan takes about three months, and a substantial part of that time is spent on this correspondence.
Nearly all of these delays can be avoided, because the packages that cause them are rarely doing anything ambitious: they compare an estimate with a stored value to eight decimals, or they read an internal slot that has moved. Two rules prevent most problems. First, access lavaan only through its public interface, and never through the internal slots of its objects. Second, write unit tests that check what the package does with the numbers of lavaan, and not the numbers themselves; a numerical comparison should use a tolerance that reflects statistical precision, not floating-point precision, because estimates can change in the later decimals whenever an optimizer, a starting value or a default setting is revised.
20.2.2 The public interface
The public interface of lavaan consists of the exported functions, the arguments that are documented on their help pages, and the documented structure of what they return. Everything else (the slots of the fitted object, the internal functions that are not exported, the order in which quantities are computed) is implementation detail that can change between versions without a deprecation warning.
For a package that post-processes fitted models, the interface is essentially the set of extractor functions of chapter 9: parameterEstimates() and standardizedSolution() for the estimates and their standard errors, parTable() for the parameter table, coef() and vcov(), fitted(), fitMeasures(), lavResiduals(), lavPredict(), lavScores(), and lavNames(). Two functions deserve a special mention. The first is the pair lavInspect() and lavTech() (Section 9.12; the keywords are listed in appendix G), which is the official access route to everything else in the fitted object. lavInspect() formats its output for reading: it adds labels, and it drops the list over the groups if there is only one group. lavTech() always returns plain matrices in a list over the groups. For code that must work for any model, lavTech() is the better choice, because the shape of its output does not depend on the number of groups. The second is lavInspect(fit, "options"), which returns the complete list of options with every "default" replaced by the value that was actually used. A package that needs to know whether a robust test statistic, a mean structure or full information maximum likelihood was used should consult this list, and not try to derive the answer from the call.
In addition, lavaan exports a number of lav_* functions that are meant for developers: matrix utilities (lav_mat_vech(), lav_mat_dup() and related functions; appendix B), functions for numerical derivatives (lav_func_grad_complex(), lav_func_jacobian_complex()), and functions that construct or combine parameter tables (lav_pt_independence(), lav_pt_unrestricted(), lav_pt_merge()). They were exported because other packages asked for them, and an exported function is kept backward compatible.
If a quantity cannot be reached through the public interface, the advice is not to bypass the interface, but to ask for an accessor: open an issue in the repository, and explain what is needed and why. Adding a keyword to lavInspect(), or exporting an existing internal function, requires little work, and it turns a private workaround into a documented feature that is protected by the test suite of lavaan. Several of the exported functions exist for this reason.
20.2.3 Do not rely on the slots
The fitted object is an S4 object, and R makes it easy to look inside: fit@ParTable$est contains the same numbers as parTable(fit)$est. But the slots are not part of the documented interface. Their organization has changed repeatedly over the history of the package (in early versions, for example, the estimates, the standard errors and the test statistics were all stored in a single slot, and they were later moved to separate slots), and it will change again. None of these changes affected the extractor functions, and each of them broke code that had bypassed the extractor functions.
What makes slot access hazardous is that nothing warns the developer. Calling an internal function with the ::: operator at least results in a note from R CMD check. Reading a slot results in nothing at all: the package installs, passes its checks, and works, until an update of lavaan reorganizes the object. At that point the package fails or, which is worse, silently computes something else. So do not write this:
# reaches into internal slots
est <- fit@ParTable$est
S <- fit@SampleStats@cov[[1]]
chisq <- fit@test[[1]]$stat
opt <- fit@Options$estimatorbut this:
# the same information, through the public interface
est <- parTable(fit)$est
S <- lavTech(fit, "sampstat")[[1]]$cov
chisq <- lavTech(fit, "test")[[1]]$stat
opt <- lavInspect(fit, "options")$estimatorThe two versions are equally short, but only the second one is covered by the regression tests of lavaan, and only the second one will keep working across releases.
Two remarks complete this advice. First, a package that needs to attach its own results to a fitted object (posterior draws, information about imputations, cached quantities) can use the @external slot, a list that is reserved for add-on packages and that lavaan itself never touches; use an element with the name of the package, because other packages share the same list. Second, do not keep fitted objects across versions. An object that was saved with saveRDS() and that is loaded again under a later version of lavaan still has the old internal layout, and the methods of the new version may read it incorrectly. The safe approach is to save the ingredients (the data, the model syntax, the options) and to fit the model again. This applies in particular to the unit tests of a package: a fitted object should never be stored as a test fixture.
20.3 A brief history of lavaan
The preceding chapters have described lavaan as it stands today, frozen at version 0.7-4. But the package was not designed in advance and implemented in one step; it grew, one release at a time, over more than fifteen years. It is worth looking back at where it came from.
lavaan grew out of the author’s dissatisfaction, around 2008, with the state of structural equation modeling in R. At the time, the only general-purpose option was the sem package, which was useful but limited. For the SEM-related parts of statistical consultancy, and for teaching a data analysis course that included a chapter on confirmatory factor analysis, something more flexible was needed: in particular, something that could be extended by the author without first having to convince the maintainer of another package.
The first attempt was a small, non-public R package called cfa2000, released in March 2009. As the name suggests, it could do exactly one thing: confirmatory factor analysis. The model was specified by passing a named list of indicator vectors to a cfa() function. By August 2009, the list-based syntax had been replaced by something closer to R’s formula language (visual =~ x1 + x2 + x3), and it became clear that a more general package was needed: one that could also handle structural relations, exogenous covariates, and the full range of structural equation models.
This more general package, initially called semplus, appeared in September 2009. Its first user-facing model syntax used list() constructs to organize the measurement part, the structural part, and the residual covariance structure. By March 2010, however, this had been replaced by a single string-based model syntax, essentially the same syntax that lavaan uses today. Shortly afterwards, the package was renamed lavaan, short for latent variable analysis, to reflect its broader scope; and on 11 May 2010, version 0.3-1 (about 6 470 lines of R code) was released on CRAN.
For a year or so, lavaan attracted little attention. A turning point came at the Psychoco 2011 workshop in Tübingen, where Achim Zeileis proposed a special issue of the Journal of Statistical Software on psychometric computing in R. The lavaan paper (Rosseel, 2012) appeared in that issue, alongside several other contributions that would later grow into an ecosystem of related packages. A visit to the University of Kansas in March 2012 led to a long collaboration with Terrence Jorgensen and, through it, to the semTools package. From 2013 onwards, an increasing number of workshops, courses, and publications adopted lavaan as their software.
The years that followed were dominated by feature growth. Support for ordered-categorical data was added in version 0.5, requiring careful attention to thresholds, polychoric correlations, and the asymptotic covariance matrix of the sample statistics. Multilevel SEM, multiple-group models, full-information maximum likelihood for missing data, several families of robust standard errors and test statistics, equality constraints across groups and blocks, and a growing collection of fit measures and diagnostic tools were all added over time. By the present version (0.7-4), the package consists of roughly 100 000 lines of code, and more than 200 packages on CRAN depend on or extend it in some way.
Table 20.1 compresses this history into a timeline: for each milestone release, it lists the major features that first appeared in it. A more detailed record, covering every CRAN release and including, in the spirit of the previous section, the bugs that were discovered in each of them, is kept in the version history section of https://lavaan.org.
| When | Version | Major new features |
|---|---|---|
| March 2009 | cfa2000 |
non-public precursor package: confirmatory factor analysis only, list-based model specification |
| September 2009 | semplus |
non-public precursor package: general SEM |
| May 2010 | 0.3-1 | first CRAN release, under the new name lavaan; the string-based model syntax; FIML for missing data |
| February 2011 | 0.4-7 | rewritten codebase; lavaanify(); robust (MLM, MLF, MLR) estimators; fitMeasures(), modindices() |
| 2011 | 0.4-8 – 0.4-11 | equality constraints via shared labels; anova(); defined parameters (:=); bootstrap standard errors and tests; simulateData() |
| May 2012 | 0.4-14 | maintenance release accompanying the JSS paper (Rosseel, 2012) |
| September 2012 | 0.5-9 | ordered-categorical endogenous variables: thresholds, Delta parameterization, DWLS/WLSMV and friends |
| December 2012 | 0.5-11 | pairwise maximum likelihood (PML) |
| March 2014 | 0.5-16 | lavTestLRT(), lavTestWald(), lavCor(); Theta parameterization |
| 2015 | 0.5-18 / 0.5-19 | lavPredict() for factor scores; lavTestScore(); efficient handling of linear equality constraints |
| September 2016 | 0.5-21 | robust CFI/TLI/RMSEA; conditional_x |
| February 2017 | 0.5-23 | lavaanList(): the same model fitted to many datasets |
| May 2018 | 0.6-1 | two-level SEM; sampling weights; rewritten robust standard errors and test statistics |
| July 2018 | 0.6-2 | cluster-robust standard errors; lower()/upper() modifiers |
| July 2019 | 0.6-4 | first (experimental) support for rotation, EFA/ESEM, and SAM |
| May 2020 | 0.6-6 | automatic parameter bounds for small samples |
| June 2021 | 0.6-9 | sam() becomes public; FIML for two-level models |
| January 2023 | 0.6-13 | efa(); lavPredictY(); Browne’s residual-based test statistics |
| June 2024 | 0.6-18 | new syntax parser; analysis of correlation structures |
| September 2025 | 0.6-20 | new implementation of composites (<~) |
| July 2026 | 0.7-2 | snake_case argument names; MIIV-2SLS (estimator = "IV"); two-level (D)WLS and categorical data; random slopes (rv()); lavEffects() |
| October 2026 | 0.7-3 | ML for correlation structures; Browne’s residual test as a second default test for ML; non-iterative estimators (MGM, JS/JSA) with standard errors; data-defined parameters (:~) |
| December 2026 | 0.7-4 | lavSimulate() for simulation studies; approximate bootstrap methods; sampling weights for two-level models; multiple-group alignment |
Today lavaan is widely used in academia and increasingly outside it: in pharmaceutical research, in health and educational testing, and in industry. With that growth has come a different set of challenges: questions of software validation, of long-term sustainability, and of organizational support for an open-source project. In December 2025, the Dutch Research Council (NWO) awarded an Open Science Infrastructure grant to a consortium of eleven Dutch professors, led by Terrence Jorgensen, with the explicit goal of building a sustainable infrastructure for SEM software based on lavaan. What began as a one-person effort is now developed by a small team, and its development is more active than ever.
20.4 Closing words
This book set out to show that nothing unexplained happens between a lavaan model syntax and the numbers in the output, only a pipeline of well-defined steps, each of which can be written down, inspected, and checked. If we have done our job, the distance between a formula in a methods paper and the line of R code that implements it should now feel small, and the output of summary() should read as a list of traceable quantities rather than as a verdict.
Structural equation modeling has a reputation for being a black-box technique, practiced by running software with default settings and trusting the output. It does not have to be. The defaults in lavaan are choices, made for reasons that this book has tried to spell out; every one of them can be overridden, and every number can be recomputed by hand from quantities that the fitted object makes available. A user who knows this is harder to mislead, whether by software, by reviewers, or by their own models.
We leave you with a map of the implementation, direct access to the sources, and, we hope, the confidence to look inside whenever the output surprises you. Thank you for reading.
The end.