Many claims in the SEM literature rest on Monte Carlo evidence: that a test statistic keeps its nominal Type I error rate, that a standard error is unbiased, that one estimator outperforms another in small samples. lavaan is not only the object of many such studies; it is also, for many researchers, the software with which they are carried out. This chapter documents that use of lavaan. It is written for readers who want to use lavaan inside a simulation study, or in any other setting where the same model is fitted to many datasets (the bootstrap and multiple imputation are the two other common cases).
A simulation study has four ingredients:
A data generator: a function that returns a new dataset each time it is called. The datasets are draws from a population that is known to the researcher.
An analysis model, and the settings (estimator, standard errors, test statistics, missing data handling) that are used to fit it.
The ‘true’ values: the values of the parameters of the analysis model in the population. Bias and coverage are defined with respect to these values.
Summaries over the replications: the bias of the estimates, the quality of the standard errors, the coverage of the confidence intervals, the rejection rates of the test statistics, the distribution of the fit measures.
Two functions cover these ingredients. The function lavaanList() (with its wrappers semList() and cfaList()) fits the same model to many datasets and stores, for each dataset, only what was asked for (Section 19.2). It is a general tool that has no notion of populations or ‘true’ values. The function lavSimulate() is built on top of it and adds everything that is specific to a simulation study: it calls the data generator, it determines the ‘true’ values automatically, and its summary() method prints the usual Monte Carlo summaries (Section 19.3). The data generator can be the generator that comes with lavaan, which starts from a population model written in lavaan model syntax, but it can also be any R function that returns a data frame. Writing such a function is the topic of Section 19.5, and it is the main reason why most simulation designs can be handled by lavSimulate() without writing a loop by hand.
The remaining sections discuss what else can be collected from each replication (Section 19.6), designs with several conditions (Section 19.7), the bootstrap as a simulation in which the observed data play the role of the population (Section 19.8), computational shortcuts (Section 19.9), reproducibility (Section 19.10), and the treatment of replications that fail (Section 19.11).
Throughout the chapter, the number of replications is denoted by R. To keep the rendering time of this book within bounds, the examples use a few hundred replications. A real study would use (at least) a thousand, which is also the default of lavSimulate().
19.2 Fitting the same model to many datasets: lavaanList()
The function lavaanList() takes a model and a collection of datasets, fits the model to each dataset, and returns an object of class lavaanList. The wrappers semList() and cfaList() do the same, but they fit the model with sem() and cfa() respectively, so that the usual defaults of these functions apply. (For lavaanList() itself, the cmd= argument selects the fitting function; its default is "lavaan".) The datasets can be provided in two ways:
data_list=: a list of data frames that already exist. This is the natural interface for multiple imputation, where the datasets are the imputed datasets (the lavaan.mi package uses the function in this way), and for datasets that were generated by other software.
data_function= together with ndat=: a function that returns one dataset per call. The function is called ndat times, with the arguments given in the list data_function_args=. The datasets are generated when they are needed, and they are never held in memory all at once.
The following example uses the second form. The population is a one-factor model with three indicators, written in lavaan model syntax with all parameter values fixed (see Section 19.5.1), and the data function calls the generator of lavaan with a sample size of 200:
lavaanList (0.7-4) -- based on 200 datasets (200 converged)
The first dataset is fitted in the ordinary way. For all later datasets, the options and the parameter table of this first fit are reused, so that the model syntax is parsed only once. All other arguments of the fitting function (estimator=, missing=, std_lv=, …) can be added to the call, and they are applied to every dataset. The option warn = FALSE was added here for this reason: without it, the warnings that lavaan produces for individual datasets (in a small sample, typically about a negative variance) are all shown at the end of the run.
What is kept from each fit is controlled by two arguments. The argument store_slots= names the parts of each fitted object that are stored: any subset of "partable", "data", "samplestats", "vcov", "test", "optim", "implied", "loglik", "h1", "baseline", "timing" and "cache", or "all". The default is "partable": the parameter table, which contains the estimates and their standard errors. The argument fun= is a function that is applied to each fitted object while it is still available; its result is stored too. This is the way to collect anything that is not part of the stored slots (here: a fit measure). The fitted objects themselves are not kept, so a study with many replications should store as little as possible.
The coef() method returns the estimates of the free parameters as a matrix with one column per dataset:
The summary() method of an ordinary lavaanList object prints the same averages (in a column est.ave), laid out like the parameter estimates of a single fit. The results of fun= are stored as a list with one element per dataset (see the implementation notes at the end of this chapter for how to reach them), and lavListInspect() and lavListTech() give access to the information that is common to all datasets (the options, the parameter table, the names of the groups).
In principle, this is all that is needed for a simulation study: the matrix of estimates (and, with coef() replaced by a function that extracts the standard errors, the matrix of standard errors) can be summarized by hand. But the averages above show that one more ingredient is needed before a bias can be computed. The average estimate of the loading of y2 is close to 0.875, while the value in the population model is 0.7. This is not bias. The population model fixes the variance of the factor to one, while the analysis model fixes the loading of y1 to one, and in that parameterization the loading of y2 equals 0.7/0.8 = 0.875 in the population. Every Monte Carlo summary presupposes that the estimates and the ‘true’ values are expressed in the same parameterization, and translating the values of the population model into the parameterization of the analysis model by hand is tedious and error-prone as soon as the model is larger than this one. The function lavSimulate() takes over this step, and the summaries that follow from it.
19.3 Simulation studies: lavSimulate()
19.3.1 A first example
The function lavSimulate() needs an analysis model and a data generator. In the simplest case, the generator is the one that comes with lavaan, and all that must be provided is a population model (pop_model=) and a sample size (sample_nobs=). The population model of this section has two factors and a regression between them. The analysis model has the same structure; it adds a label to the regression coefficient and it defines a new parameter (the square of this coefficient):
The analysis model is fitted with sem() (this can be changed with the cmd= argument: "sem", "cfa", "growth", "lavaan" or "sam"), and all other arguments of the fitting function can be added to the call. The result is again a lavaanList object, so everything of the previous section applies (coef(), fun=, store_slots=). In addition, the object records that it is the result of a simulation, and it contains the ‘true’ values. The summary() method uses them:
lavaanList (0.7-4) -- based on 500 datasets (500 converged)
True values: analysis model fitted to the population moments.
Test statistics (the average and the variance of the test statistic, and the
proportion of datasets where the model is rejected at the 0.10, 0.05 and 0.01
level): The analysis model holds in the population: the rejection rates
should be close to the nominal levels.
test nrep df stat_ave stat_var reject_10 reject_05
standard 500 8.000 7.966 15.036 0.100 0.048
browne.residual.nt.model 500 8.000 7.851 14.211 0.086 0.046
reject_01
0.010
0.006
Fit measures (average, standard deviation, and the 5th, 50th and 95th
percentile):
measure nrep ave sd q05 q50 q95
cfi 500 0.995 0.008 0.976 1.000 1.000
tli 500 1.001 0.023 0.956 1.005 1.032
rmsea 500 0.018 0.025 0.000 0.000 0.068
srmr 500 0.031 0.009 0.018 0.030 0.046
Latent Variables:
est_true est_ave est_bias se_obs se_ave se_bias
f1 =~
y1 1.000 1.000 0.000 0.000 0.000 NA
y2 0.875 0.879 0.004 0.128 0.125 0.977
y3 0.750 0.752 0.002 0.121 0.113 0.929
f2 =~
y4 1.000 1.000 0.000 0.000 0.000 NA
y5 0.875 0.887 0.012 0.121 0.112 0.932
y6 0.750 0.753 0.003 0.102 0.102 1.000
ci_lower ci_upper coverage
NA NA NA
0.635 1.124 0.946
0.531 0.972 0.926
NA NA NA
0.667 1.108 0.940
0.553 0.952 0.950
Regressions:
est_true est_ave est_bias se_obs se_ave se_bias
f2 ~
f1 (b) 0.400 0.401 0.001 0.101 0.102 1.005
ci_lower ci_upper coverage
0.201 0.601 0.954
Variances:
est_true est_ave est_bias se_obs se_ave se_bias
.y1 0.360 0.346 -0.014 0.090 0.086 0.949
.y2 0.510 0.509 -0.001 0.079 0.079 0.992
.y3 0.640 0.633 -0.007 0.080 0.078 0.969
.y4 0.360 0.359 -0.001 0.088 0.086 0.979
.y5 0.510 0.497 -0.013 0.077 0.079 1.018
.y6 0.640 0.634 -0.006 0.075 0.078 1.040
f1 0.640 0.646 0.006 0.121 0.121 1.003
.f2 0.640 0.637 -0.003 0.125 0.117 0.934
ci_lower ci_upper coverage
0.178 0.514 0.946
0.355 0.663 0.954
0.480 0.786 0.930
0.190 0.527 0.958
0.343 0.651 0.940
0.481 0.787 0.948
0.409 0.883 0.940
0.408 0.867 0.916
Defined Parameters:
est_true est_ave est_bias se_obs se_ave se_bias
bsq 0.160 0.171 0.011 0.085 0.083 0.978
ci_lower ci_upper coverage
0.008 0.334 0.932
The simulate_args= argument was used here to switch off a number of columns, so that the table fits the page. All columns are described in the next section.
19.3.2 Reading the summary
The summary has four parts.
The header shows the number of datasets, and how many of them could be used (see Section 19.11). The next line tells where the ‘true’ values come from. In this example, they were obtained by fitting the analysis model to the population moments, and they are exact (Section 19.4).
The second part concerns the test statistics. For each test statistic that was requested (test=), it shows the degrees of freedom, the average and the variance of the statistic over the replications, and the proportion of datasets in which the model was rejected at the 0.10, 0.05 and 0.01 level. If the statistic follows a chi-square distribution, its average should be close to the degrees of freedom, and its variance close to twice the degrees of freedom. The note above the table tells how the rejection rates should be read: if the analysis model holds in the population, they are empirical Type I error rates, which should be close to the nominal levels; if not, they reflect the power of the test. In this example, the second row is a residual-based test statistic (Section 8.5.10), which is part of the current default set of test statistics.
The third part shows the average, the standard deviation and three percentiles of the fit measures that were computed for each dataset. The default set is CFI, TLI, RMSEA and SRMR (chapter 10); the argument fit_measures= of lavSimulate() changes it.
The last part has one row per parameter, in the layout of the parameter estimates of a single fit. Let \hat{\vartheta}_r be the estimate of a parameter in replication r, \widehat{\text{se}}_r its standard error, and \vartheta_0 its ‘true’ value. The columns are listed in Table 19.1.
Table 19.1: The columns in the parameter section of the summary of a simulation.
Column
Definition
est_true
the ‘true’ value \vartheta_0
est_ave
the average of the estimates, \bar{\vartheta} = R^{-1} \sum_r \hat{\vartheta}_r
est_bias
the bias, \bar{\vartheta} - \vartheta_0
rel_bias
the relative bias, (\bar{\vartheta} - \vartheta_0)/\vartheta_0 (not available if \vartheta_0 = 0)
rmse
the root mean squared error, \sqrt{R^{-1} \sum_r (\hat{\vartheta}_r - \vartheta_0)^2}
se_obs
the standard deviation of the estimates over the replications (the empirical standard error)
se_ave, se_med
the average and the median of the standard errors \widehat{\text{se}}_r
se_bias, se_bias_med
the ratios se_ave/se_obs and se_med/se_obs
wald
the average of the Wald statistics \hat{\vartheta}_r / \widehat{\text{se}}_r
prop_sig
the proportion of datasets in which the parameter is significantly different from zero
ci_lower, ci_upper
the average bounds of the confidence intervals \hat{\vartheta}_r \pm z \, \widehat{\text{se}}_r
coverage
the proportion of these intervals that contain \vartheta_0
est_bias_mcse
the Monte Carlo standard error of est_ave (and of est_bias): se_obs divided by \sqrt{R}
se_bias_mcse
the Monte Carlo standard error of se_bias
coverage_mcse
the Monte Carlo standard error of coverage, \sqrt{c(1-c)/R} with c the coverage
Three remarks may help to read these columns. First, se_bias is a ratio, not a difference: a value of one means that the standard errors are, on average, equal to the standard deviation of the estimates; a value below one means that they are too small. The median-based variant se_bias_med is less sensitive to a few replications with a very large standard error, which may occur for defined parameters that are nonlinear functions of the model parameters. Second, fixed parameters (here: the two marker loadings) have no standard error, and their se_bias and coverage are not available. Third, the defined parameter bsq is treated like any other parameter: its ‘true’ value is 0.4^2 = 0.16, and its standard errors are based on the Delta method (Section 8.4.14).
The Monte Carlo standard errors deserve attention. A simulation study is itself a statistical experiment with a finite number of replications, and its results are estimates (Morris et al., 2019). With R = 500, a coverage of 0.95 is estimated with a standard error of about \sqrt{0.95 \times 0.05/500} \approx 0.01, so an observed coverage of 0.93 is not strong evidence against the nominal level. The _mcse columns give these standard errors for each parameter, and they are part of the default output.
The simulate_args= argument of summary() is a list. Its logical elements est_bias, rel_bias, rmse, se_bias, se_bias_med, prop_sig, coverage, mcse, standardized, test and fit_measures switch the corresponding columns or parts on or off. The element level (default 0.95) sets the level of the confidence intervals and of the significance tests behind prop_sig, and trim (default 0) requests trimmed averages and standard deviations. With estimates = FALSE, the parameter section is omitted altogether. With print = FALSE, nothing is printed, and the tables are returned as a list, which is the convenient form for further processing:
test df stat_ave reject_05
1 standard 8 7.965657 0.048
2 browne.residual.nt.model 8 7.851443 0.046
The two rows of the parameter table illustrate the use of the Monte Carlo standard errors. The bias of b is well within two Monte Carlo standard errors of zero. The bias of the defined parameter bsq is not: the square of an unbiased estimator is biased upwards by the variance of that estimator, and the squared value in the se_obs column of b is indeed close to the bias that is observed for bsq.
19.4 The ‘true’ values
The est_true column contains the values of the parameters of the analysis model in the population. As the example of Section 19.2 showed, they cannot simply be copied from the population model, for several reasons:
The two models may use a different parameterization. In the example of the previous section, the population model fixes the variances of the factors, while the analysis model fixes the first loading of each factor. The ‘true’ value of the loading of y2 is therefore 0.875 and not 0.7, and the ‘true’ value of the variance of f1 is 0.8^2 = 0.64 and not 1.
The analysis model may contain equality constraints, or defined parameters (bsq in the example), that have no counterpart in the population model.
The analysis model may be misspecified on purpose. Many simulation studies are about exactly this, for example the effect of an omitted cross-loading on the structural coefficients. In that case, the estimates do not converge to the values of the population model, but to the values that minimize the discrepancy between the analysis model and the population. These are called the pseudo-true values, and they depend on the estimator.
The data generator may not be based on a lavaan model at all.
For these reasons, lavSimulate() determines the ‘true’ values from the analysis model, in one of three ways.
If the population moments are available (the covariance matrix, and if needed the means and the thresholds), the analysis model is fitted once to these moments, in the way a model is fitted to summary statistics (Section 5.2). The resulting estimates are the ‘true’ values. They are exact, and they are automatically expressed in the parameterization of the analysis model, with all its constraints and defined parameters. The generator of lavaan always provides the population moments. A generator written by the user can provide them too (Section 19.5.2).
If the analysis model does not reproduce the population moments, the summary says so. The following example adds a cross-loading to the population model, and keeps the analysis model as it was:
lavaanList (0.7-4) -- based on 200 datasets (200 converged)
True values: analysis model fitted to the population moments (estimator ML).
The analysis model does not hold in the population (largest residual =
0.094): these are pseudo-true values. Population RMSEA = 0.072.
Test statistics (the average and the variance of the test statistic, and the
proportion of datasets where the model is rejected at the 0.10, 0.05 and 0.01
level): The analysis model does not hold in the population: the rejection
rates reflect the power of the test.
test nrep df stat_ave stat_var reject_10 reject_05
standard 200 8.000 16.466 58.837 0.630 0.500
browne.residual.nt.model 200 8.000 16.653 61.447 0.615 0.510
reject_01
0.250
0.270
The header reports the largest difference between the population moments and the moments implied by the analysis model, and (for estimator ML) the population value of the RMSEA. The note above the test statistics has changed too: the rejection rates are now estimates of the power of the test to detect this misspecification at N = 200. The pseudo-true value of the regression coefficient is no longer 0.4:
pe <- out_mis$pepe[pe$label =="b", c("label", "est_true", "est_ave", "est_bias","se_bias", "coverage")]
The est_bias and coverage columns are computed with respect to this pseudo-true value. They tell whether the estimator and its standard errors behave well around the value the estimator converges to. The effect of the misspecification itself is the difference between the pseudo-true value and the value in the population model (0.4), and it is obtained without any simulation error. If the bias with respect to the value of the population model is wanted instead, that value can be provided with the est_true= argument, as shown below.
If the population moments are not available, or if they cannot be used, the analysis model is fitted once to a single large simulated dataset of about est_true_nobs observations (the default is one million). The generator of lavaan is called with a larger sample size; for other generators, many datasets are stacked. These values are not exact, but they are precise enough for most purposes, and the summary tells how precise they are (Section 19.5.5). This route is taken for a generator that does not provide the population moments, for multilevel data, for ordered variables that are treated as continuous in the analysis model, and for ordered variables with nonnormal latent responses.
If this fails too, a warning is given, the ‘true’ values are set to NA, and the simulation is still carried out. All summaries that do not need the ‘true’ values (the standard deviations of the estimates, the average standard errors and their ratio, the test statistics, the fit measures) are still available.
In all three cases, the stream of random numbers is not disturbed: the generated datasets are the same, whether the ‘true’ values are computed or provided by the user.
The user can overrule the automatic values with the est_true= argument. A numeric vector without names must contain a value for each row of the parameter table of the analysis model. A vector with names replaces the values of these parameters only; the names are either the labels of the parameters, or their names as shown by coef():
The summary mentions how many values were provided by the user.
19.5 The data generator
19.5.1 The built-in generator
The default data generator of lavSimulate() is the function lavSimulateData() (also available under its older name simulateData()). Its first argument is a population model in lavaan model syntax, where the population values are supplied as fixed values, using the pre-multiplication mechanism of chapter 2. The syntax is converted to a parameter table and to model matrices, the model-implied moments are computed (Chapters 3 and 4, with the population values in the place of the estimates), and the data are drawn from a distribution with these moments. The function can also be called directly:
Data <-lavSimulateData(pop_model, sample_nobs =200, seed =1234)round(head(Data, 3), 3)
The data generator of version 0.7-4 is described here only briefly, because it is the part of the simulation tools that is most likely to be extended. What matters for the rest of this chapter is its interface: a function that takes a population model and a sample size, and returns a data frame. The main features are the following.
Normal data are the default. The arguments skewness= and kurtosis= (a single value, or one value per observed variable) request nonnormal data with the given marginal skewness and excess kurtosis, using the method of Vale and Maurelli (1983).
Ordered data are generated if the population model contains thresholds (the | operator). The model then describes the latent responses of chapter 14, which are generated first and then cut at the thresholds. The generated columns are plain integer codes, so the variables must be declared as ordered in the analysis (ordered = TRUE, or the names of the variables; Section 14.3).
Multiple groups are generated if sample_nobs= is a vector, with the values per group supplied through the c() modifier in the population model. A group column is added to the data.
Two-level data are generated if the population model contains level: blocks (chapter 16). The argument cluster_idx= assigns each observation to a cluster, and a cluster column is added to the data.
With empirical = TRUE (normal data only), the sample covariance matrix of the generated data is exactly equal to the population covariance matrix. This is useful to illustrate a population result with a single dataset, but it has no place in a simulation study, where the sampling variability is the object of interest.
In lavSimulate(), these arguments are passed to the generator through the data_function_args= list, for example data_function_args = list(skewness = 2, kurtosis = 7). The arguments pop_model= and sample_nobs= are shortcuts for the elements model and sample_nobs of this list.
One pitfall deserves a warning: specify every parameter of the population model. A parameter that is not mentioned in the syntax, but that lavaan adds automatically (residual variances, variances and covariances of latent variables, intercepts), receives a default value: one for a variance, zero for a covariance or an intercept. If the lines with the residual variances were omitted from pop_model, all residual variances would be equal to one, and the reliability of the indicators (often the very quantity a simulation is designed to manipulate) would be much lower than intended. With return_fit = TRUE, the population model is attached to the generated data as an attribute, so that the complete set of population values and the population moments can be inspected:
Data <-lavSimulateData(pop_model, sample_nobs =200, seed =1234,return_fit =TRUE)fit_pop <-attr(Data, "fit")lavInspect(fit_pop, "implied")$cov
This attribute is also how lavSimulate() obtains the population moments, as discussed next.
19.5.2 Writing a data generator
The data_function= argument of lavSimulate() (and of lavaanList()) accepts any function that returns a dataset. The requirements are few:
The function returns a data frame (or a matrix with column names) that contains the observed variables of the analysis model, and whatever else the analysis needs (a grouping variable, a cluster variable, sampling weights).
Each call returns a new, independent dataset, generated with the random number generator of R (rnorm(), runif(), sample(), and so on), so that the seed of the simulation controls the data (Section 19.10).
The function is called with the arguments in data_function_args=. If pop_model= or sample_nobs= are used in the call of lavSimulate(), they are added to this list as model and sample_nobs, so a generator that has arguments with these names can be used with the two shortcuts.
Optionally, the function passes the population moments to lavSimulate(), by attaching one of two attributes to the dataset.
The two attributes are the following. The attribute "fit" is the lavaan object of the population model, as returned by lavSimulateData() with return_fit = TRUE. The attribute "pop_moments" is a list with an element cov (the population covariance matrix, with the names of the variables as row and column names), and optionally mean (a named vector with the population means), th and nobs. The element th is needed for ordered data: it is a named list that contains, for each ordered variable, its standardized thresholds, and the rows and columns of these variables in cov must then contain the correlations of the latent responses. For multiple groups, each element is itself a list with one element per group, and nobs gives the (relative) sizes of the groups.
This leads to three kinds of generators, which are illustrated in the next three sections: a generator that modifies the data of the built-in generator and passes on the "fit" attribute; a generator that is written from scratch and provides "pop_moments"; and a generator that provides nothing, so that the ‘true’ values are based on a large simulated dataset.
It is the responsibility of the author of the generator that the attribute describes the population from which the data are drawn. If the function changes the data in a way that changes their covariance matrix (by adding outliers, for example, or by categorizing a variable), the attribute must be changed accordingly, or omitted.
19.5.3 Modifying the generated data: missing values
The first generator calls lavSimulateData() and then removes values. The probability that y1 and y2 are missing depends on the value of y4, which is always observed, so the values are missing at random (MAR). About one third of the cases have missing values. Because removing values does not change the population from which the complete data were drawn, the function copies the "fit" attribute to its result:
gen_mar <-function(model, sample_nobs =300) { Data <-lavSimulateData(model, sample_nobs = sample_nobs,return_fit =TRUE) out <- Data miss <-runif(sample_nobs) <plogis(-1+1.5* Data$y4) out[miss, c("y1", "y2")] <-NAattr(out, "fit") <-attr(Data, "fit") out}
The generator has arguments model and sample_nobs, so the shortcuts pop_model= and sample_nobs= can be used. The same generator is now used twice: once with listwise deletion (the default), and once with full information maximum likelihood (Section 7.3.4):
The ‘true’ value is the same in both rows, and it is exact: it was obtained from the population moments of the complete data. With listwise deletion, the cases that remain are a selected subsample (cases with a high value of y4 are underrepresented), the regression coefficient is biased, and the coverage of its confidence interval is far below the nominal level. With full information maximum likelihood, which is consistent under MAR, the bias disappears.
The same pattern (generate, modify, copy the attribute) serves for planned missing data designs, for attrition in longitudinal data, or for adding variables that are not part of the population model.
19.5.4 A generator written from scratch: heavy tails
The second kind of generator does not use lavaan at all. This is needed whenever the distribution of the data must be controlled in more detail than the skewness and the kurtosis of each variable. The example is a classic topic: the behavior of the normal-theory chi-square test statistic when the data are not normal (Section 8.5.3). Two generators are compared. Both draw data from the population of pop_model, so they have the same population covariance matrix, and both produce variables with heavy tails. They differ in how the nonnormality arises.
The population covariance matrix is computed first, from the model matrices of chapter 4:
The first generator draws from a multivariate t distribution with df degrees of freedom, rescaled so that its covariance matrix is \boldsymbol{\Sigma}. A draw from this distribution is a multivariate normal vector, multiplied by a random scale factor that is common to all its elements. The variables are uncorrelated where the model says so, but they are not independent: a case with a large scale factor has large values on all factors and all residuals at the same time.
gen_t <-function(nobs =200, df =8) { Z <-matrix(rnorm(nobs *6), nobs, 6) %*%chol(Sigma) Y <- Z *sqrt((df -2) /rchisq(nobs, df))colnames(Y) <- ov_names Y <-as.data.frame(Y)attr(Y, "pop_moments") <-list(cov = Sigma) Y}
The second generator follows the model equations. The two disturbances of the factors and the six residuals are drawn independently of each other, each from a standardized chi-square distribution with df degrees of freedom (a skewed distribution with an excess kurtosis of 12/df), and the observed variables are computed from them:
Both functions attach the population covariance matrix as the "pop_moments" attribute. With the default values of df, the excess kurtosis of the observed variables is about twice as large for the second generator as for the first:
The analysis model is fitted with estimator = "MLM", which gives the standard test statistic and the Satorra-Bentler scaled test statistic (Section 8.5.4). No population model is needed in the call, and the sample size is passed through data_function_args=:
lavaanList (0.7-4) -- based on 300 datasets (300 converged)
True values: analysis model fitted to the population moments.
Test statistics (the average and the variance of the test statistic, and the
proportion of datasets where the model is rejected at the 0.10, 0.05 and 0.01
level): The analysis model holds in the population: the rejection rates
should be close to the nominal levels.
test nrep df stat_ave stat_var reject_10 reject_05 reject_01
standard 300 8.000 11.952 42.554 0.333 0.243 0.090
satorra.bentler 300 8.000 8.379 16.275 0.133 0.050 0.007
summary(sim_indep, estimates =FALSE)
lavaanList (0.7-4) -- based on 300 datasets (300 converged)
True values: analysis model fitted to the population moments.
Test statistics (the average and the variance of the test statistic, and the
proportion of datasets where the model is rejected at the 0.10, 0.05 and 0.01
level): The analysis model holds in the population: the rejection rates
should be close to the nominal levels.
test nrep df stat_ave stat_var reject_10 reject_05 reject_01
standard 300 8.000 8.077 17.351 0.120 0.060 0.013
satorra.bentler 300 8.000 8.197 16.954 0.133 0.053 0.010
The analysis model holds in both populations, so every rejection is a Type I error. For the multivariate t data, the standard test statistic rejects the model far too often, and its average is well above the degrees of freedom; the scaled test statistic is close to the nominal levels. For the data of the second generator, which are more nonnormal by the usual measures, the standard test statistic behaves well without any correction. This is the asymptotic robustness of normal-theory methods (Anderson & Amemiya, 1988; Satorra & Bentler, 1990): if the factors and the residuals are mutually independent (and not merely uncorrelated), and their variances and covariances are free parameters, the normal-theory test statistic keeps its chi-square distribution, and the normal-theory standard errors of the loadings and the regression coefficients remain valid. The kurtosis of the observed variables does not tell the two situations apart. A study that only varies the marginal skewness and kurtosis therefore covers a small part of the possible nonnormal distributions, and conclusions about “nonnormal data” depend on the generator that was used (see also Foldnes & Grønneberg, 2018). A data generator written by the researcher is the means to extend the study in this direction.
19.5.5 Generators without population moments
The third kind of generator provides no information about the population. This is the only option if the population moments are difficult to derive, for example because the data are contaminated, truncated, or transformed. In the following generator, five percent of the cases of each dataset are replaced by cases from a population with a much larger variance. No attribute is attached:
lavaanList (0.7-4) -- based on 300 datasets (300 converged)
True values: analysis model fitted to a large simulated dataset (200000
observations); they are not exact: their standard errors are about 0.032
times the values in the se_obs column.
The header reports how the ‘true’ values were obtained: the generator was called many times (at most max(1000, ndat) times, or until est_true_nobs observations are reached), the datasets were stacked, and the analysis model was fitted once to this large dataset. The resulting values have a sampling error of their own, and the header expresses it relative to the se_obs column: with 1000 stacked datasets, the standard error of a ‘true’ value is about 1/\sqrt{1000} \approx 0.032 times the standard deviation of the corresponding estimate. This is of the same size as the Monte Carlo error of the average estimate itself (est_bias_mcse), so a bias that is small relative to these two numbers should not be interpreted. For a generator that is slow, est_true_nobs= can be lowered, at the price of less precise ‘true’ values.
In this example, the ‘true’ values of the variances are no longer the values of the uncontaminated population (0.36, 0.51, …): the contamination inflates all variances and covariances by the same factor, and the ‘true’ values describe the contaminated population. The regression coefficient is not affected (its ‘true’ value differs from 0.4 only by the sampling error of the large dataset). The table also shows that, for these data and this sample size, the robust standard errors of estimator = "MLM" are too small, and that the coverage of the confidence intervals is below the nominal level.
A special case concerns covariates. If the analysis model contains exogenous covariates and fixed_x = TRUE (the default for most estimators), the standard errors are conditional on the observed values of the covariates. To match this, lavSimulate() keeps the values of the covariates fixed across the datasets (for continuous data, a single group and a single level), and only the other variables are generated anew, conditional on the covariates. With fixed_x = FALSE, the covariates are generated anew in each dataset.
19.6 Collecting more from each replication
By default, lavSimulate() stores the parameter table and the test statistics of each fit (store_slots = c("partable", "test")), and it computes four fit measures. Three arguments extend or reduce this.
The argument fit_measures= is a character vector with the names of the fit measures that are computed for each dataset, using the names accepted by fitMeasures() (Section 10.2). With fit_measures = NULL, no fit measures are computed. This also saves time, because the baseline model does not have to be fitted (Section 19.9), provided that baseline = FALSE is added to the call.
The argument standardized= requests the standardized solution (chapter 12) for each dataset, together with its standard errors. With standardized = TRUE (or "std_all"), the completely standardized solution is used; the alternatives are "std_lv" and "std_nox". The ‘true’ values are standardized in the same way, and the summary shows a second parameter table for the standardized estimates:
In the standardized metric, the ‘true’ values of the loadings are the values that were written in the population model for the indicators of f1 (whose variance is one in the population), but not for the indicators of f2, whose total variance is 1 + 0.4^2 = 1.16.
The argument fun= works as in lavaanList(): a function of the fitted object, whose result is stored for each dataset. It gives access to everything that is not covered by the standard summaries, such as modification indices, factor score determinacies, or the result of a model comparison. In the following example, the function returns the number of iterations and a flag that tells whether the solution is admissible:
Finally, the cmd= argument determines the function that fits the analysis model. With cmd = "sam", the model is fitted with the structural-after-measurement approach of chapter 18, and the ‘true’ values are obtained by applying sam() to the population moments. Comparing two estimators then amounts to two calls of lavSimulate() with the same generator and the same seed.
19.7 Several conditions
A simulation study usually crosses several factors: sample sizes, population values, distributions, estimators. The function lavSimulate() runs a single cell of such a design. The design itself is an ordinary loop over the cells, in which the summary of each cell is stored as a data frame. The following example continues the study of Section 19.5.4, and crosses the two generators with four sample sizes:
Figure 19.1: Empirical rejection rates (at the 0.05 level) of the standard and the scaled test statistic, for two nonnormal data generators and four sample sizes. The dashed line is the nominal level. Each point is based on 200 replications.
A few practical remarks apply to any design of this kind.
Each cell is a separate call, so the cells can be run in any order, on different machines, or resumed after an interruption. Storing the summary of each cell (or the complete object, with saveRDS()) as soon as it is finished costs little and protects against lost work.
Using the same iseed in every cell is harmless. Using a different seed per cell is equally valid; what matters is that the seed of each cell is recorded.
With 200 replications, the Monte Carlo standard error of a rejection rate near 0.05 is about \sqrt{0.05 \times 0.95 / 200} \approx 0.015. The difference between the two test statistics for the multivariate t data is many times larger than this; the small differences between them for the other generator are not.
The figure also shows that the inflated rejection rate of the standard test statistic for the multivariate t data does not decrease with the sample size. It is not a small-sample problem.
The parameter tables of the cells (summary(sim, print = FALSE)$pe) can be stacked in the same way if the study is about bias or coverage.
19.8 Resampling instead of simulating: bootstrapLavaan()
A bootstrap study is a simulation study in which the observed dataset takes the place of the population. bootstrapLavaan() takes a fitted lavaan object, resamples the data R times, refits the model, and applies fun= to every refit:
HS_model <-' visual =~ x1 + x2 + x3 textual =~ x4 + x5 + x6 speed =~ x7 + x8 + x9 'fit <-cfa(HS_model, data = HolzingerSwineford1939)boot <-bootstrapLavaan(fit, R =100, fun ="coef", iseed =8482)dim(boot) # one row per bootstrap draw
[1] 100 21
round(apply(boot[, 1:4], 2, sd), 3) # bootstrap SEs of first parameters
fun= can be any function of the fitted object (the default "coef" extracts the free parameters; fitMeasures or a custom function work equally well). The type= argument selects the resampling scheme: "ordinary" (nonparametric case resampling; the default), "bollen.stine" (data transformed so that the model holds exactly; the scheme used by the Bollen-Stine test of Section 8.5.12), "parametric" (draws from a fitted multivariate normal distribution), and "yuan" (the intermediate transformation of Yuan and colleagues, controlled by h0_rmsea=). Replications in which the refit fails are dropped from the result, but they are recorded: the returned matrix carries an "error.idx" attribute with the indices of the failed draws, and a "nonadmissible" attribute with the indices of the solutions that converged but are not admissible (see Section 19.11). With keep_idx = TRUE, the resampled case indices of every draw are stored as well, so that any single replication can be reconstructed. For the ordinary bootstrap of the parameter estimates (fun = "coef"), the method= argument can replace the refits by an approximation ("ij" or "hoij2"; see Section 8.4.13).
When se = "bootstrap" is requested in a fitting function, lavaan calls this same function internally and stores the draws in the fitted object (they can be retrieved with lavInspect(fit, "coef_boot"); Section 8.4.12). This also works inside lavSimulate(): with se = "bootstrap", the bootstrap confidence intervals of each dataset are stored, and the summary reports their coverage next to that of the symmetric intervals. Such a study is expensive, because the number of fits is the product of the number of datasets and the number of bootstrap draws.
19.9 Speed: switching off what you do not need
A default sem() call does much more than estimate parameters: it estimates the unrestricted (\mathsf{H}_1) model, fits the baseline (independence) model, computes standard errors and one or more test statistics, and runs a number of checks on the solution. In an interactive analysis this is all useful. In a simulation that only needs, say, the parameter estimates, it is wasted time, repeated in every replication. Most of it can be switched off:
Table 19.2: Switches that reduce the computation time per fit.
These are ordinary arguments of the fitting functions, so they can be added to a call of lavSimulate() or lavaanList(). In lavSimulate(), two of its own arguments belong to the same list: fit_measures = NULL (no fit measures are computed) and standardized = FALSE (the default). The gain depends on the model: the larger the model, and the more time-consuming the standard errors and the scaled test statistics, the larger the reduction. Even for the small model of this chapter, a study that only looks at the point estimates runs noticeably faster:
Two words of caution. First, only switch off what the study does not need: a coverage study needs se, a Type I error study needs test, a study of fit measures needs baseline and h1. Disabling the checks (check_post in particular) also means that inadmissible solutions are no longer flagged; if you disable them, record these flags yourself (Section 19.11). Second, when in doubt, profile first: for large categorical models, the time-consuming step may be the computation of the polychoric correlations and their \boldsymbol{\Gamma} matrix (chapter 14), which none of these switches avoid.
Three further sources of speed need no action. In lavaanList(), lavSimulate() and bootstrapLavaan(), the work that is identical for all replications (parsing the model syntax, building the parameter table, processing the options) is done only once. A hand-written loop that calls sem() for every dataset repeats this work every time, which is one more reason to prefer these functions. In lavSimulate(), the ‘true’ values are used as the starting values of every replication (unless start= is provided), which reduces the number of iterations. And the replications can be distributed over several cores with parallel = "multicore" (not available on Windows) or parallel = "snow", together with ncpus=. The default value of ncpus= is at most two; set it to the number of cores that may be used.
19.10 Reproducibility
A simulation study should be reproducible down to the last digit. The relevant settings are the following.
The iseed= argument of lavSimulate(), lavaanList() and bootstrapLavaan() is the recommended way to fix the seed. With the same iseed, and the same settings for parallel= and ncpus=, the same datasets are generated, whatever the state of the random number generator of R at the moment of the call.
Without iseed=, a call of set.seed() before the call of lavSimulate() or lavaanList() has the same effect for a serial run.
A serial run and a parallel run with the same iseed do not produce the same datasets, and neither do two parallel runs with a different number of cores, or with a different type of parallelization. The way in which the replications were distributed is therefore part of what must be recorded.
A data generator written by the user must draw all its random numbers from the random number generator of R. A generator that sets a seed of its own (or that calls lavSimulateData() with its seed= argument) returns the same dataset in every replication.
Record the environment: the lavaan version (packageVersion("lavaan")), the R version, and the options that were used belong in the output of every study. Defaults do change between versions (the version history at https://lavaan.org documents when and how), and a study that sets its options explicitly survives such changes better than one that relies on the defaults.
Note that the promise (same seed and same settings, same results) is the durable part. The mechanism (the global random number generator of R for serial runs, L’Ecuyer-CMRG streams for parallel runs) is the current implementation. Should the mechanism ever change, results that were seeded under the old one would no longer be reproducible under the new one. This is one more reason to record the lavaan version next to the seed.
19.11 Failed replications
In any realistic simulation, some replications fail: the optimizer does not converge, or it converges to a solution that is not admissible (a negative residual variance, a covariance matrix of the latent variables that is not positive definite). These events are outcomes, not nuisances. Their rate depends on the condition (sample size, model misspecification), and it is often worth reporting in its own right. More importantly, the replications that fail are not a random subset, so the summaries of the remaining replications describe a selected set of datasets.
lavaanList() (and therefore lavSimulate()) distinguishes three reasons why a dataset is not used: the model did not converge; an error occurred while the model was fitted; or, for ordered data, a variable has fewer response categories in this dataset than in the first one (an empty category, so that the number of thresholds differs). The estimates of these datasets are NA in the output of coef(). The header of the summary shows how many datasets were not used, and why, and all summaries are based on the remaining datasets. With store_failed = TRUE, the dataset (and, if available, the fitted object) of every failed replication is written to the temporary directory of the R session (tempdir()), so that the problem can be studied afterwards.
Solutions that converged but are not admissible are used. If they should be counted, or excluded, collect the flag with fun=, as in the example of Section 19.6 (lavInspect(fit, "post_check")).
The other tools behave as follows. bootstrapLavaan() drops the failed draws from the matrix that it returns, but records their indices in the "error.idx" attribute; draws that converged to a solution that is not admissible are kept, and flagged in the "nonadmissible" attribute. In a hand-written loop, test for lavInspect(fit, "converged") and lavInspect(fit, "post_check"), and store both flags along with the results.
When nonconvergence is frequent, the remedies of Chapters 6 and 7 apply inside a simulation as well: bounded estimation (bounds = "standard"), or multiple random starts (rstarts=; Section 6.3), at a computational cost that must be weighed against the time that is available per replication (Section 7.11). Whatever is chosen becomes part of the estimator that is studied, and should be reported as such.
19.12 Implementation notes
This section collects details that are tied to the current implementation of lavaan (the R package, version 0.7-4) rather than to the concepts of the main text. Internal file and function names may change or move at any release, while everything reachable through the user interface stays put. Table 19.3 maps the tools of this chapter to their source files.
Table 19.3: Source files behind the simulation tools.
File
Contents
lav_lavaanList_simulate.R
lavSimulate(), and the functions that determine the ‘true’ values
xxx_lavaanList.R
lavaanList(), semList(), cfaList() and the parallel loop
lav_lavaanList_methods.R lav_lavaanList_inspect.R
coef(), summary() (including the summaries of a simulation), lavListInspect()/lavListTech()
lav_data_simulate.R
the built-in data generator (single-level and multilevel workers)
lav_bootstrap.R
bootstrapLavaan(), incl. the Bollen-Stine and Yuan transformations
lav_bootstrap_ij.R
the approximate bootstrap draws (method = "ij" and "hoij2")
lav_efa_bootstrap.R
bootstrap functions for rotated (EFA/ESEM) solutions
A lavaanList object stores the results of fun= in its @funList slot (a list with one element per dataset), and the stored parts of each fit in slots with matching names (@ParTableList, @testList, @vcovList, …). The @meta slot is a list with the status of the datasets: ok (a logical vector that coef() and summary() consult) and status (one of "ok", "no convergence", "error" or "empty category" for each dataset). For an object created by lavSimulate(), the @meta slot also contains the ‘true’ values (est_true), a list that describes their origin (est_true_info, with elements such as source, misspecified, max_resid and rmsea), the matrix of fit measures (fit_measures, one row per dataset), and the standardized estimates and their standard errors (std). None of these has a public accessor in version 0.7-4, apart from what summary() returns with print = FALSE; this is why one example of this chapter reads @funList directly.
The fit measures and the standardized solutions are collected by the same mechanism as the function of the user: lavSimulate() wraps them in a single function that is passed to lavaanList(), and separates the results afterwards.
To decide whether a data generator can return the population model, lavSimulate() checks whether the function has an argument called return_fit. If so, this argument is switched on for the single call that is used to determine the ‘true’ values. A generator written by the user that passes its arguments on to lavSimulateData() can use the same convention instead of attaching the "fit" attribute in every call.
When the analysis model is fitted to the population moments, a few settings are adapted. For ordered data, and for the estimators WLS, DWLS and PML, the weight matrix is not available at the population level, and unweighted least squares is used instead; if the analysis model holds in the population, this gives the same values. If it does not hold, the pseudo-true values of the estimator of the analysis may be different, and the summary says so.
19.12.1 Recycling slots across replications
lavaanList(), lavSimulate() and bootstrapLavaan() avoid redundant work by passing parts of the first fitted object to the later fits. In version 0.7-4, the same mechanism is available to a hand-written loop: the lavaan() function accepts a family of slot_* arguments (slot_options, slot_par_table, slot_sample_stats, slot_data, slot_model, slot_cache and sloth1) that take the corresponding slots of a previous fit, so that these steps are skipped. Any part that is not supplied is built as usual.
fit0 <-sem(model, data = Data)# internal slots; no public accessor yet (one is planned)fit1 <-lavaan(slot_options = fit0@Options,slot_par_table = fit0@ParTable,data = new_data)
If only the data change, recycling the options and the parameter table is safe. Recycling the other parts (slot_sample_stats, slot_model) is only meaningful if the data are unchanged too; this is used internally when the same model must be estimated again under different options. These arguments are tied to the slots of the current fitted object and may change at a major version; code that should keep working is better written with lavaanList() or lavSimulate().
Anderson, T. W., & Amemiya, Y. (1988). The asymptotic normal distribution of estimators in factor analysis under general conditions. The Annals of Statistics, 16(2), 759–771. https://doi.org/10.1214/aos/1176350834
Foldnes, N., & Grønneberg, S. (2018). The asymptotic covariance matrix and its use in simulation studies. Structural Equation Modeling: A Multidisciplinary Journal, 25(6), 881–896. https://doi.org/10.1080/10705511.2018.1467872
Morris, T. P., White, I. R., & Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38(11), 2074–2102. https://doi.org/10.1002/sim.8086
Satorra, A., & Bentler, P. M. (1990). Model conditions for asymptotic robustness in the analysis of linear relations. Computational Statistics & Data Analysis, 10(3), 235–249. https://doi.org/10.1016/0167-9473(90)90004-2
Vale, C. D., & Maurelli, V. A. (1983). Simulating multivariate nonnormal distributions. Psychometrika, 48(3), 465–471. https://doi.org/10.1007/BF02293687