# Load all libraries for this example
library(INLAvaan)
library(tidyverse)
library(lavaan)SEMs are ubiquitous in the social sciences, psychology, ecology, and other fields. The {INLAvaan} package (Jamil & Rue, 2026) provides a user-friendly interface for fitting Bayesian SEMs using Integrated Nested Laplace Approximations (INLA, Rue et al., 2009), based on a bespoke approximate Bayesian inference framework for SEMs (Jamil & Rue, in press). This vignette will guide you through the basics of using {INLAvaan} to fit a simple SEM. Before we begin make sure you have installed the INLAvaan package from GitHub by running the commands below.
# Load all libraries for this example
library(INLAvaan)
library(tidyverse)
library(lavaan)To motivate the use of SEMs, consider the introductory example in Song & Lee (2012): Does poorer glycemic control lead to greater severity of kidney disease? We observe three indicators of glycemic control (y1, y2, y3) and three indicators of kidney disease severity (y4, y5, y6).
| Indicator | Description | Unit | |
|---|---|---|---|
| y1 | HbA1c | 3-month avg. blood glucose | % |
| y2 | FPG | Fasting plasma glucose | mmol/L |
| y3 | Insulin | Fasting insulin level | μU/mL |
| y4 | PCr | Plasma creatinine | μmol/L |
| y5 | ACR | Albumin–creatinine ratio | mg/g |
| y6 | BUN | Blood urea nitrogen | mmol/L |
Rather than fitting separate regression models for each indicator, SEM allows us to model the relationship between the latent constructs themselves, providing a clearer and more coherent representation of the underlying processes. The hypothesised SEM is illustrated by the figure below:
For the two-factor SEM we described above, it is easy to simulate some data using the {lavaan} package to do so. The code is below:
pop_mod <- "
eta1 =~ 1*y1 + 0.8*y2 + 0.6*y3
eta2 =~ 1*y4 + 0.8*y5 + 0.6*y6
eta2 ~ 0.3*eta1
# Variances
y1 ~~ 0.5*y1
y2 ~~ 0.5*y2
y3 ~~ 0.5*y3
y4 ~~ 0.5*y4
y5 ~~ 0.5*y5
y6 ~~ 0.5*y6
eta1 ~~ 1*eta1
eta2 ~~ 1*eta2
"
set.seed(123)
dat <- lavaan::simulateData(pop_mod, sample.nobs = 1000)
str(dat)
#> 'data.frame': 1000 obs. of 6 variables:
#> $ y1: num -1.141 -0.478 1.478 0.272 -0.544 ...
#> $ y2: num -1.3002 -0.9876 0.288 0.0841 -2.3112 ...
#> $ y3: num -0.8088 -0.0217 -0.1574 0.9953 -0.2583 ...
#> $ y4: num -0.3956 0.0812 -1.6447 -0.8119 2.3699 ...
#> $ y5: num -0.0924 0.7101 -0.0221 -1.1631 -1.0067 ...
#> $ y6: num -0.523 0.985 -1.183 0.856 0.967 ...From the code above, note the true values of the parameters, including the factor loadings Λ, regression coefficient β between the two latent variables, as well as the residual and latent variances Θ and Ψ respectively.
Now that we have simulated some data, we can fit the SEM using INLAvaan. The model syntax is similar to that of {lavaan}, making it easy to specify the model. For further details on the model syntax, refer to the lavaan website. {INLAvaan} provides mirror functions for the main model fitting functions in {lavaan}:
acfa() mirrors lavaan::cfa() for confirmatory factor analysis; andasem() mirrors lavaan::sem() for structural equation models;agrowth() mirrors lavaan::growth() for latent growth curve models.The code to fit the SEM model is below:
mod <- "
eta1 =~ y1 + y2 + y3
eta2 =~ y4 + y5 + y6
eta2 ~ eta1
"
fit <- asem(mod, dat)
#> ✔ Found the posterior mode in 69 iterations [76ms]
#> ✔ Applied VB mean correction; max |δ| = 0.1σ [18ms]
#> ✔ Fitted 13 skew-normal posterior marginals [57ms]
#> ⠙ Drawing from the posterior and summarising.
#> ✔ Summarised 1,000 draws from the posterior [97ms]
#> ℹ Computed posterior fit measures: PPP, DIC.As with lavaan::sem(), this model is fitted without a mean structure by default (meanstructure = FALSE). Rather than profiling the means out as lavaan does, {INLAvaan} assigns the saturated means flat priors and marginalises them analytically, which keeps the likelihood a proper Bayesian object. Intercepts can instead be modelled explicitly with meanstructure = TRUE. See the mean structures article for how the two treatments relate and when model comparisons across them are meaningful.
{INLAvaan} computes an approximation to the posterior density by way of a Laplace approximation (Tierney et al., 1989). The joint mode and the Hessian needs to be computed, which gives a Gaussian distribution for the joint posterior of the parameters. The mode is found with stats::nlminb(). A variational Bayes (VB) correction then moves the mean of this Gaussian. By default it takes one step from the mode (vb_correction = "onestep"). This step is checked, so that it does not move too far from the posterior mean. When the check fails, the fit solves the VB equation in full instead, as vb_correction = "full" does, and warns. To leave the correction out, use vb_correction = "none".
From this, the marginal posterior distribution of each parameter is obtained in one of two ways:
marginal_method = "skewnorm", the default). The log-posterior of each parameter is scanned from the mode, and a skew normal density is fitted to the scanned points by weighted least squares on the log scale. This is curve fitting, unlike the simplified Laplace approximation of INLA, which matches the derivatives of the log density at the mode (Rue et al., 2009, Section 3.2.3). The scan runs along a line through the mode on which the other parameters sit at their conditional means under the joint Gaussian (Martins et al., 2013, Section 3.2.2). Along this line the posterior volume of the other parameters changes, and marginal_scan chooses how that change is taken into account:
"plain" ignores it, and uses the heights of the log-posterior along the line as they are."linear" (the default) adds a linear correction for the change in volume, at almost no extra cost."exact" computes the volume term exactly at each point of the line, instead of linearly."laplace" leaves the straight line: at each point it moves the other parameters to their conditional mode, and takes the height and the volume there. This is the Laplace approximation of the marginal (Tierney & Kadane, 1986)."exact" and "laplace" take 10 to 25 times as long as "linear".marginal_method = "gaussian"), which need no scan.Once the marginal posterior distributions have been obtained, we can further use these to compute any derived quantities of interest via copula sampling: the fitted marginals are joined by a Gaussian copula with the correlations of the joint Gaussian (Chiuchiolo et al., 2023). The posterior predictive p-values (Gelman et al., 1996) and Deviance Information Criterion (DIC, Spiegelhalter et al., 2002) are computed this way. The test argument names which of these post-estimation quantities to compute: the default test = "standard" computes the PPP and the DIC, test = "full" adds the leave-one-out cross-validation and WAIC results (see the model comparison section below) and stores them with the fit, and test = "none" skips them all. Often, the posterior sampling takes longer than the model fitting itself, so the number of samples can be controlled via the nsamp argument (default is nsamp = 1000).
The resulting object is of class INLAvaan, a subclass of lavaan objects.
str(fit, 1)
#> Formal class 'INLAvaan' [package "INLAvaan"] with 21 slots
fit
#> INLAvaan 0.4.2 ended normally after 69 iterations
#>
#> Estimator BAYES
#> Optimization method NLMINB
#> Number of model parameters 13
#>
#> Number of observations 1000
#>
#> Model Test (User Model):
#>
#> Marginal log-likelihood -8081.339
#> PPP (Chi-square) 0.121Therefore, most of the methods that work for lavaan objects will also work for INLAvaan objects. The most common ones are probably coef() and summary().
# Inspect coefficients
coef(fit)
#> eta1=~y2 eta1=~y3 eta2=~y5 eta2=~y6 eta2~eta1 y1~~y1 y2~~y2
#> 0.865 0.576 0.800 0.611 0.318 0.489 0.443
#> y3~~y3 y4~~y4 y5~~y5 y6~~y6 eta1~~eta1 eta2~~eta2
#> 0.493 0.480 0.505 0.481 1.058 1.024
# Summary of results
summary(fit)
#> INLAvaan 0.4.2 ended normally after 69 iterations
#>
#> Estimator BAYES
#> Optimization method NLMINB
#> Number of model parameters 13
#>
#> Number of observations 1000
#>
#> Model Test (User Model):
#>
#> Marginal log-likelihood -8081.339
#> PPP (Chi-square) 0.121
#>
#> Information Criteria:
#>
#> Deviance (DIC) 16069.236
#> Effective parameters (pD) 13.061
#>
#> Parameter Estimates:
#>
#> Marginalisation method SKEWNORM
#> Marginal scan LINEAR
#> VB correction ONESTEP
#>
#> Latent Variables:
#> Estimate SD 2.5% 97.5% NMAD Prior
#> eta1 =~
#> y1 1.000
#> y2 0.865 0.041 0.786 0.948 0.005 normal(0,10)
#> y3 0.576 0.031 0.517 0.638 0.003 normal(0,10)
#> eta2 =~
#> y4 1.000
#> y5 0.800 0.039 0.726 0.878 0.005 normal(0,10)
#> y6 0.611 0.031 0.552 0.672 0.003 normal(0,10)
#>
#> Regressions:
#> Estimate SD 2.5% 97.5% NMAD Prior
#> eta2 ~
#> eta1 0.318 0.040 0.241 0.397 0.001 normal(0,10)
#>
#> Variances:
#> Estimate SD 2.5% 97.5% NMAD Prior
#> .y1 0.489 0.047 0.398 0.582 0.004 gamma(1,.5)[sd]
#> .y2 0.443 0.037 0.372 0.516 0.003 gamma(1,.5)[sd]
#> .y3 0.493 0.026 0.444 0.547 0.000 gamma(1,.5)[sd]
#> .y4 0.480 0.049 0.385 0.576 0.005 gamma(1,.5)[sd]
#> .y5 0.505 0.036 0.435 0.577 0.002 gamma(1,.5)[sd]
#> .y6 0.481 0.027 0.430 0.536 0.000 gamma(1,.5)[sd]
#> eta1 1.058 0.077 0.912 1.215 0.003 gamma(1,.5)[sd]
#> .eta2 1.024 0.076 0.882 1.178 0.003 gamma(1,.5)[sd]It’s possible to request posterior medians and modes in the summary output by specifying postmedian = TRUE or postmode = TRUE in the summary() function.
Predicted values for the latent variables can be obtained using the predict() function. This is done by sampling from the posterior distributions of the latent variables given the observed data. The function also supports predictions for observed variables (e.g. type = "ov") and missing data imputation, respecting multilevel structure if present.
eta_preds <- predict(fit, nsamp = 100)
#> ✔ Obtained 100 draws of the latent variables [19ms]
length(eta_preds)
#> [1] 100
head(eta_preds[[1]])
#> eta1 eta2
#> [1,] -0.87388740 -0.9810775
#> [2,] -0.53788863 1.0354989
#> [3,] 0.71539830 -1.0325585
#> [4,] 0.73112778 -0.5508644
#> [5,] -0.01774483 0.1443918
#> [6,] 1.71538447 1.5187613This is an S3 object with a summary method that provides posterior means and credible intervals for the latent variables. Alternatively, the user is welcome to perform their own summary statistics on the list of posterior samples returned by predict().
summ_eta <- summary(eta_preds)
str(summ_eta)
#> List of 7
#> $ group_id: NULL
#> $ Mean : num [1:1000, 1:2] -1.142 -0.557 0.473 0.254 -1.074 ...
#> ..- attr(*, "dimnames")=List of 2
#> .. ..$ : NULL
#> .. ..$ : chr [1:2] "eta1" "eta2"
#> $ SD : num [1:1000, 1:2] 0.452 0.41 0.446 0.409 0.413 ...
#> ..- attr(*, "dimnames")=List of 2
#> .. ..$ : NULL
#> .. ..$ : chr [1:2] "eta1" "eta2"
#> $ 2.5% : num [1:1000, 1:2] -1.874 -1.299 -0.55 -0.573 -1.868 ...
#> ..- attr(*, "dimnames")=List of 2
#> .. ..$ : NULL
#> .. ..$ : chr [1:2] "eta1" "eta2"
#> $ 50% : num [1:1000, 1:2] -1.226 -0.577 0.482 0.226 -1.038 ...
#> ..- attr(*, "dimnames")=List of 2
#> .. ..$ : NULL
#> .. ..$ : chr [1:2] "eta1" "eta2"
#> $ 97.5% : num [1:1000, 1:2] -0.143 0.372 1.191 1.018 -0.171 ...
#> ..- attr(*, "dimnames")=List of 2
#> .. ..$ : NULL
#> .. ..$ : chr [1:2] "eta1" "eta2"
#> $ Mode : num [1:1000, 1:2] -1.269 -0.572 0.497 0.143 -0.965 ...
#> ..- attr(*, "dimnames")=List of 2
#> .. ..$ : NULL
#> .. ..$ : chr [1:2] "eta1" "eta2"
#> - attr(*, "class")= chr "summary.predict.inlavaan_internal"
head(summ_eta$Mean)
#> eta1 eta2
#> [1,] -1.1418047 -0.3537043
#> [2,] -0.5572092 0.4883867
#> [3,] 0.4727418 -0.9477327
#> [4,] 0.2536589 -0.4047482
#> [5,] -1.0741537 0.7083917
#> [6,] 1.5640064 1.4570325The generative side of the model is exposed by sampling(), which draws parameters, latent variables, or observed variables from the posterior (or prior) generative SEM, and by simulate(), which produces complete replicate data sets from the fitted model.
yrep <- simulate(fit, nsim = 1, seed = 1)
head(yrep[[1]])
#> y1 y2 y3 y4 y5 y6
#> 1 -0.24709223 -1.5686526 -0.06714442 1.5618391 1.2055896 0.7941617
#> 2 -2.36342238 -1.0970945 -1.47288377 0.5744609 1.2537885 1.1356330
#> 3 1.49242599 -0.8458421 0.57549121 2.6692672 2.2446799 1.9629489
#> 4 0.01279552 -0.6156390 -0.21093528 2.7687749 0.2361583 0.3798813
#> 5 2.88871763 1.3165239 1.26488817 1.2994183 0.0591500 0.1433680
#> 6 1.41895902 1.5439769 1.42633167 1.6012491 0.8260100 1.0609464Comparing such replicates with the observed data is the basis of prior and posterior predictive checking. The predictive checks article walks through that workflow, and the sampling article explains the machinery behind it.
Global fit measures are collected by fitmeasures(): the PPP and DIC mentioned earlier, Bayesian analogues of the classical fit indices (BRMSEA, BGammaHat, and related indices, Garnier-Villarreal & Jorgensen, 2020), and the LOO and WAIC measures of the model comparison section below when these are stored with the fit.
fitmeasures(fit)
#> npar margloglik ppp dic p_dic BRMSEA
#> 13 -8081.339 0.121 16069.236 13.061 0.032
#> BGammaHat adjBGammaHat BMc BCFI BTLI BNFI
#> 0.997 0.992 0.995 0.996 0.992 0.992Definitions and worked examples are in the Bayesian fit indices article.
The diagnostics() function reports convergence and approximation-quality metrics for the fitted model. Global diagnostics (type = "global") check whether the optimiser converged, and quantify how well the skew-normal marginals match the joint posterior (via KL divergence and NMAD), including how much mass a fitted marginal leaves beyond the window that was scanned to fit it (unscanned_mass_max). Per-parameter diagnostics (type = "param") provide gradient norms and KL contributions for each free parameter, which is useful for identifying any problematic parameters. {inlavanilla} runs the same approximation pipeline on any log-likelihood, and its diagnostics article explains each check and what to do when one flags a problem.
diagnostics(fit)
#> npar converged iterations grad_inf
#> 13 1 69 3.89e-03
#> grad_inf_rel grad_l2 mode_shift_max hess_cond
#> 1.21e-01 7.75e-03 3.69e-04 2.94e+01
#> hess_cond_cor vb_applied vb_shift_max vb_kld_global
#> 1.03e+01 1 0.1023 0.0120
#> kld_max kld_mean nmad_max nmad_mean
#> 0.0052 0.0012 0.0050 0.0028
#> unscanned_mass_max grad_gap_max vb_fallback vb_step_max
#> 2.73e-04 1.08e-03 0 NA
#> vb_lhat vb_j0 vb_j1 vb_solve
#> 0.0096 -0.0010 0.0125 0
#> mean_gap_max ridge_bend_max n_heavy_tails nsamp
#> 0.0016 0.0281 0 1000
#> psi_npd_share theta_npd_share vb_mcse_max vb_mcse_mean
#> 0.0000 0.0000 NA NAThe timing() function reports how long each computation stage took, which can help identify bottlenecks when scaling to larger models.
timing(fit)
#> total
#> 0.28 sA simple plot method is provided to view the marginal posterior distributions of the parameters. The vertical lines indicate the posterior mode.
plot(fit)In addition to several global fit indices (i.e. PPP, DIC), it is possible to compare models by way of Bayes factors using the compare() function. This function takes two INLAvaan objects and computes the Bayes factor using the Laplace approximations to the marginal likelihoods.
mod2 <- "
# A model with uncorrelated factors
eta1 =~ y1 + y2 + y3
eta2 =~ y4 + y5 + y6
eta1 ~~ 0*eta2
"
fit2 <- asem(mod2, dat)
#> ✔ Found the posterior mode in 68 iterations [26ms]
#> ✔ Applied VB mean correction; max |δ| = 0.079σ [9ms]
#> ✔ Fitted 12 skew-normal posterior marginals [44ms]
#> ⠙ Drawing from the posterior and summarising.
#> ✔ Summarised 1,000 draws from the posterior [82ms]
#> ℹ Computed posterior fit measures: PPP, DIC.
compare(fit, fit2)
#> Bayesian Model Comparison (INLAvaan)
#> Models ordered by marginal log-likelihood
#>
#> Model npar Marg.Loglik logBF DIC pD
#> fit 13 -8081.339 0.00 16069.24 13.061
#> fit2 12 -8108.789 -27.45 16132.95 11.823As a note, there have been several criticisms of the use of Bayes factors for model comparison, particularly in the context of SEMs (Schad et al., 2023; Tendeiro & Kiers, 2019). Leave-one-out cross-validation (LOO, Vehtari et al., 2017) and the widely applicable information criterion (WAIC, Watanabe, 2010) are popular alternatives which compare models on out-of-sample predictive accuracy instead; see Merkle et al. (2019) for their use with latent variable models. Both are implemented in {INLAvaan}. The functions loo() and waic() require neither refitting nor sampling: both are computed in closed form from the same Taylor expansion around the fit’s Laplace summary.
loo(fit)
#> ── Leave-one-subject-out ────────────────────────── 1000 subjects, second-order ──
#>
#> Estimate SE
#> elpd_loo -8024.9 54.3
#> p_loo 13.0 0.5
#> looic 16049.7 108.6
#>
#> ── Curvature check ───────────────────────────────────────────────────────────────
#>
#> first-to-second-order gap 6.6
#> pD/2 (trace) 6.5
#> excess over pD/2 (trace) +1.2%
#>
#> ℹ The gap approaches pD/2 (trace) from above. A large excess says the
#> second-order expansion has not settled over the sample.To compare models on this predictive scale, pass loo = TRUE to compare(). Models are sorted by expected log predictive density (ELPD), with paired standard errors for the ELPD differences.
compare(fit, fit2, loo = TRUE)
#> Bayesian Model Comparison (INLAvaan)
#> Models ordered by ELPD (Taylor LOO, second-order)
#> elpd_diff/se_diff are paired differences vs the best model
#>
#> Model npar Marg.Loglik logBF DIC pD ELPD SE p_loo elpd_diff
#> fit 13 -8081.339 0.00 16069.24 13.061 -8024.860 54.291 13.008 0.000
#> fit2 12 -8108.789 -27.45 16132.95 11.823 -8057.002 55.129 12.039 -32.143
#> se_diff
#> 0.000
#> 7.735See the cross-validation article for the methodology and more advanced usage, including multigroup and two-level models, missing data, and scoring submodels without refitting.
The {INLAvaan} package uses the same prior specification syntax as {blavaan} (Merkle et al., 2021; Merkle & Rosseel, 2018), as detailed here. Essentially, there are two ways to set priors for model parameters: 1) Globally for all parameters of a certain type (e.g., all factor loadings, all regression coefficients, etc.); and 2) Individually for specific parameters in the model syntax.
The default global priors are similar to those from {blavaan}:
priors_for() # similar to blavaan::dpriors()
#> nu alpha lambda beta
#> "normal(0,32)" "normal(0,10)" "normal(0,10)" "normal(0,10)"
#> wmat theta psi rho
#> "normal(0,10)" "gamma(1,.5)[sd]" "gamma(1,.5)[sd]" "beta(1,1)"
#> tau
#> "normal(0,1.5)"Note that, {INLAvaan} uses the separation strategy for variance matrices, and consequently places priors on correlations instead of covariances. If, instead we wished to set global priors, say a gamma distribution on variances instead of standard deviations (default), then we would do the following:
DP <- priors_for(theta = "gamma(1,1)", psi = "gamma(1,1)")
DP
#> nu alpha lambda beta wmat
#> "normal(0,32)" "normal(0,10)" "normal(0,10)" "normal(0,10)" "normal(0,10)"
#> theta psi rho tau
#> "gamma(1,1)" "gamma(1,1)" "beta(1,1)" "normal(0,1.5)"
## fit <- asem(mod, dat, dp = DP) # not runTo set individual priors for specific parameters, we can do so in the model syntax itself. For instance, to set a normal prior with mean 1 and standard deviation 3 for the factor loading of y3 on eta1, and a normal prior with mean 0 and standard deviation 0.5 for the regression coefficient from eta1 to eta2, we would specify the model as follows:
mod <- "
eta1 =~ y1 + y2 + prior('normal(1,3)')*y3
eta2 =~ y4 + y5 + y6
eta2 ~ prior('normal(0,.5)')*eta1
"
## fit <- asem(mod, dat) # not runDependency on R-INLA has been temporarily removed for the current version of {INLAvaan} (>= 0.2.0). For a wide class LVMs and SEMs where the latent variables are unstructured and independent, the current implementation is sufficient. However, future versions of {INLAvaan} will re-introduce dependency on R-INLA to allow for more complex latent structures, such as spatial and temporal dependencies.