Package {INLAvaan}


Type: Package
Title: Approximate Bayesian Latent Variable Analysis
Version: 0.4.2
Description: Implements approximate Bayesian inference for Structural Equation Models (SEM) using a custom adaptation of the Integrated Nested Laplace Approximation (Rue et al., 2009) <doi:10.1111/j.1467-9868.2008.00700.x> as described in Jamil and Rue (in press) <doi:10.48550/arXiv.2603.25690>. Provides a computationally efficient alternative to Markov Chain Monte Carlo (MCMC) for Bayesian estimation, allowing users to fit latent variable models using the 'lavaan' syntax. See also the companion paper on implementation and workflows, Jamil and Rue (2026) <doi:10.48550/arXiv.2604.00671>.
License: GPL (≥ 3)
URL: https://inlavaan.haziqj.ml/, https://github.com/haziqj/INLAvaan
BugReports: https://github.com/haziqj/INLAvaan/issues
Depends: R (≥ 4.1.0)
Imports: cli (≥ 3.6.0), graphics, lavaan (≥ 0.7-2), methods, parallel, stats, utils
Suggests: blavaan, future, ggplot2, knitr, lme4, numDeriv, parallelly, quarto, sn, testthat (≥ 3.2.0), withr
VignetteBuilder: quarto
Config/Needs/website: rmarkdown
Config/roxygen2/markdown: TRUE
Config/roxygen2/version: 8.1.1
Config/testthat/edition: 3
Encoding: UTF-8
NeedsCompilation: no
Packaged: 2026-12-05 07:23:58 UTC; haziqj
Author: Haziq Jamil ORCID iD [aut, cre, cph], Håvard Rue ORCID iD [ctb] (Statistical and computational methodology), Alvin Bong [ctb] (Initial site build), Alexandre B. Simas [ctb] (Tests), Thomas Luu [cph] (Skew-normal quantile approximation (Apache License 2.0))
Maintainer: Haziq Jamil <haziq.jamil@gmail.com>
Repository: CRAN
Date/Publication: 2026-12-05 07:50:02 UTC

INLAvaan: Approximate Bayesian Latent Variable Analysis

Description

logo

Implements approximate Bayesian inference for Structural Equation Models (SEM) using a custom adaptation of the Integrated Nested Laplace Approximation (Rue et al., 2009) doi:10.1111/j.1467-9868.2008.00700.x as described in Jamil and Rue (in press) doi:10.48550/arXiv.2603.25690. Provides a computationally efficient alternative to Markov Chain Monte Carlo (MCMC) for Bayesian estimation, allowing users to fit latent variable models using the 'lavaan' syntax. See also the companion paper on implementation and workflows, Jamil and Rue (2026) doi:10.48550/arXiv.2604.00671.

Main features

Model specifications

Supports advanced 'lavaan' syntax features, including:

Methods for INLAvaan objects

After fitting a model an INLAvaan object is returned. The following S4 methods are available. See INLAvaan for the class definition.

Online vignettes

The package website contains comprehensive examples covering:

Author(s)

Maintainer: Haziq Jamil haziq.jamil@gmail.com (ORCID) [copyright holder]

Authors:

Other contributors:

See Also

Useful links:


Class For Representing a (Fitted) Latent Variable Model

Description

This is a class that extends the lavaan class. Several S4 methods are available.

Usage

## S4 method for signature 'INLAvaan'
coef(object, ...)

## S4 method for signature 'INLAvaan'
nobs(object, ...)

## S4 method for signature 'INLAvaan'
show(object)

## S4 method for signature 'INLAvaan'
summary(
  object,
  header = TRUE,
  fit.measures = TRUE,
  estimates = TRUE,
  ci = TRUE,
  standardized = FALSE,
  standardised = standardized,
  rsquare = FALSE,
  postmedian = FALSE,
  postmode = FALSE,
  nmad = TRUE,
  kld = FALSE,
  vb_shift = FALSE,
  priors = TRUE,
  nd = 3L,
  level = 0.95,
  ...
)

Arguments

object

An object of class INLAvaan.

...

Additional arguments passed to methods.

header

Logical; if TRUE, print model fit information header.

fit.measures

Logical; if TRUE, print fit measures (DIC and pD; PPP is printed by the header regardless). Both require the fit to have computed them, see the test argument of inlavaan().

estimates

Logical; if TRUE, print parameter estimates table. Its numbers are those of parameterestimates(), which returns them as a data frame.

ci

Logical. If TRUE (default), show the equal-tailed credible interval at level. Its columns are titled by their quantiles, such as 2.5% and 97.5%.

standardized

Logical; if TRUE, include standardized estimates.

standardised

Alias of standardized; either spelling is accepted (the alias wins if both are supplied).

rsquare

Logical; if TRUE, include R-square values for the observed dependent variables, computed at the posterior mean point estimates.

postmedian

Logical; if TRUE, include posterior median in estimates.

postmode

Logical; if TRUE, include posterior mode in estimates.

nmad

Logical; if TRUE (default), include the NMAD column for skew-normal marginal fit quality.

kld

Logical; if FALSE (default), omit the per-parameter KLD column. Set to TRUE to show it.

vb_shift

Logical; if FALSE (default), omit the VB shift column (shift in units of posterior SD). Set to TRUE to show it.

priors

Logical; if TRUE, include prior information in estimates.

nd

Integer. The number of decimal places of the numbers in the estimates table, the estimates included.

level

The probability of the credible interval, a number between 0 and 1. Defaults to 0.95.

Slots

external

A list containing an inlavaan_internal object.

See Also

lavaan, inlavaan(), acfa(), asem(), agrowth(), parameterestimates()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "none", silent = TRUE)

# Print basic info
fit

# Detailed summary
summary(fit)

# Extract coefficients
coef(fit)



Fit an Approximate Bayesian Confirmatory Factor Analysis Model

Description

Fit an Approximate Bayesian Confirmatory Factor Analysis Model

Usage

acfa(
  model,
  data = NULL,
  dp = priors_for(),
  test = "standard",
  vb_correction = c("onestep", "full", "none"),
  marginal_method = c("skewnorm", "gaussian"),
  marginal_scan = c("linear", "exact", "laplace", "plain"),
  marginal_laplace_fallback = FALSE,
  nsamp = 1000,
  cov_as_cor = FALSE,
  sn_fit_sample = TRUE,
  control = list(),
  verbose = FALSE,
  silent = FALSE,
  cores = NULL,
  ppp_method = c("onestep", "em"),
  ppp_nsamp = 250L,
  wiggle = NULL,
  wiggle.sd = 0.1,
  n_qmc = NULL,
  vb_method = NULL,
  marginal_correction = NULL,
  samp_copula = NULL,
  samp_norta = NULL,
  sn_fit_ngrid = NULL,
  sn_fit_logthresh = NULL,
  sn_fit_temp = NULL,
  debug = NULL,
  add_priors = NULL,
  optim_method = NULL,
  numerical_grad = NULL,
  hessian_method = NULL,
  ...
)

Arguments

model

A description of the user-specified model. Typically, the model is described using the lavaan model syntax. See model.syntax for more information. Alternatively, a parameter table (e.g., the output of the lavParTable() function) is also accepted.

data

An optional data frame containing the observed variables used in the model. The variables must be continuous: an ordered factor in the model stops the fit, as this version does not fit ordinal or binary indicators (see the section "Ordinal and binary data" of inlavaan()).

dp

Default prior distributions for the different types of model parameters; a named character vector as returned by priors_for(). Types left out take their default priors. A name that is not a type, such as a misspelt one, gives a warning. dp = blavaan::dpriors() works too.

test

Character vector naming the post-estimation quantities to compute and store with the fit. The atoms are "ppp" (posterior predictive p-value), "dic" (deviance information criterion and its pD), "loo" (leave-one-out cross-validation, see loo()) and "waic" (see waic()). Three aliases stand for sets of atoms: "standard" (the default) and its synonym "default" give c("ppp", "dic"); "full" gives all four; "none" gives nothing. Aliases and atoms may be mixed and are unioned, so test = c("standard", "loo") adds the LOO to the default set. The LOO and the WAIC come from one Taylor pass, so asking for either stores both. They run only when asked for, with no time budget. On a model the casewise machinery does not support (a fit with sampling weights) they are skipped with a warning and the rest of the fit proceeds. For a two-level model the PPP follows blavaan: each of ppp_nsamp posterior draws generates replicate data, which are scored against the saturated model (see ppp_method). The two-level PPP is experimental. The fit records what was requested and what was computed (get_inlavaan_internal(fit, "test")); summary(), fitmeasures(), deviance(), logLik() and timing() report only what was computed. add_loo() stores the LOO and WAIC post hoc; loo() and waic() compute on demand. For a random-slope model "ppp" is dropped, with a warning when it was asked for and a message otherwise (see the Random slopes section of inlavaan()). "dic", "loo" and "waic" are unaffected.

vb_correction

The variational Bayes (VB) correction of the posterior mean of the Laplace approximation. "onestep" (default) takes one step from the mode and checks it. Where the check fails, the posterior is far from Gaussian along the step: the fit then solves the VB equation instead, and warns (see diagnostics()). "full" iterates the correction to its fixed point, and "none" leaves it out. The correction moves the marginal log-likelihood, the point at which the DIC is computed, the centre of the LOO and the WAIC, and the Gaussian marginals of marginal_method = "gaussian" and their draws. It does not move the skew-normal marginals or their draws, which are scanned from the mode. The intercepts of a saturated mean structure are the exception: a single-level model of one group with complete data and meanstructure = TRUE, in which every observed variable has a free intercept of its own with a normal prior, and which has no free latent mean, no observed variable in a regression, no equality constraint and no composite. They are not scanned (their nmad in diagnostics() is NA, which is the way to tell): with either marginal_method their marginals are Gaussian and centred at the VB mean. So the correction also moves these marginals, their draws and what is computed from them.

marginal_method

How the marginal posterior of each parameter is approximated. "skewnorm" (default) fits a skew-normal distribution to a scan of the log-posterior along the parameter (see marginal_scan). "gaussian" takes the Gaussian marginal of the Laplace approximation, centred at the VB mean, which is faster. [Deprecated] The old values warn: "marggaus" is the old name of "gaussian", and "asymgaus" now runs "skewnorm". "sampling" is kept for a sampler that is under development, and gives an error.

marginal_scan

How the scan behind each skew-normal marginal is taken. "linear" (default) scans along a straight line through the mode, and adds a linear correction for the changing volume of the other parameters. "exact" computes that volume term exactly at each point of the scan. "laplace" maximises the log-posterior over the other parameters at each point of the scan, and takes the height and the volume there. "plain" adds no volume correction. On the Holzinger and Swineford and the Political Democracy models, "exact" and "laplace" take 10 to 25 times as long as "linear". Ignored with marginal_method = "gaussian", which has no scan.

marginal_laplace_fallback

Logical. Rescan with marginal_scan = "laplace" only the parameters whose ridge bend is above 0.25 (see diagnostics())? Default FALSE, so that a fit costs what marginal_scan says. With TRUE, the parameters where the default scan is likely to give too small a posterior SD get the slower scan, and the others keep the fast one. The column ridge_bend of diagnostics(fit, "param") shows which parameters these are. Ignored with marginal_method = "gaussian" and with marginal_scan = "laplace".

nsamp

The number of samples to draw for all sampling-based approaches (including posterior sampling for model fit indices). A fit that summarises some parameters from the draws needs at least 2: the free covariances and the ⁠:=⁠ and ⁠~*~⁠ parameters. The intercepts that the fit centres have a draw of their own (see centring in inlavaan_control()).

cov_as_cor

Logical. Residual and latent-disturbance covariance parameters (⁠~~⁠ between two observed or two latent variables) are always estimated on the correlation scale internally (an atanh link, the same as for std.ov/std.lv-standardised parameters); by default their reported marginal is then re-derived on the covariance scale \sigma_i \sigma_j \rho from a posterior sample (see nsamp), because that is the scale lavaan/blavaan report by default. When TRUE, that re-derivation is skipped and each such parameter's own directly profiled correlation-scale marginal \rho \in (-1, 1) is reported instead – useful for comparing the profiling machinery (skew-normal fit, VB, ...) against a correlation-scale reference without the sampling/copula step in between. Model estimation is identical either way; only what is reported for these parameters changes. The returned parameter table keeps their covariance classes, so loo() and waic() after the fit score the same model, and the setting is stored as get_inlavaan_internal(fit)$cov_as_cor. The point estimates of these parameters are correlations, so methods that use the point estimates as model parameters (such as fitted() and residuals()) are not meaningful when TRUE. Not the same as lavaan's std.ov/std.lv, which re-parameterises the whole model on a standardised scale. Defaults to FALSE.

sn_fit_sample

Logical. When TRUE (default), a parametric skew-normal is fitted to the posterior samples for covariance and defined parameters. When FALSE, these are summarised using kernel density estimation instead.

control

A list of tuning settings, made by inlavaan_control(), or a plain list with some of its names: the limits of the search for the posterior mode, of the VB correction and of the skew-normal scans, and the settings hessian, debug, add_priors and centring. The defaults suit most fits. An unknown name gives an error. The controls of stats::nlminb() that control took up to INLAvaan 0.3.5, such as iter.max, still work, with a deprecation warning. See inlavaan_control().

verbose

Logical. With FALSE (default) the fit prints one line per stage. With TRUE it also prints the details of each stage of the fit on the internal scale: the start, the mode search, the VB correction and the marginals, with their checks. Use silent = TRUE to print nothing.

silent

Logical. Print nothing at all, and muffle the warnings and messages raised during the fit? Default FALSE. verbose and silent cannot both be TRUE. Errors are still raised. Whether or not silent is TRUE, the texts of the warnings raised during the fit are recorded in the field warnings of get_inlavaan_internal().

cores

A positive whole number or NULL. The number of cores. Other values, such as 0, 2.5 or NA, give an error. With NULL (default), the scans of the skew-normal marginals follow future::plan(), which is serial unless a plan is set, and the LOO and the WAIC asked for in test run serially. With cores > 1, the scans run in parallel when the packages future and parallelly are installed, and serially otherwise. The LOO and the WAIC are then forked via parallel::mclapply() where that is safe, or run over a PSOCK cluster (separate R processes) inside IDE R sessions (RStudio, Positron) and on Windows. 1 is serial.

ppp_method

How the PPP of a two-level model scores the observed and the replicate data against the saturated model. "onestep" (default) takes one Fisher-scoring step from the moments of each posterior draw towards the saturated fit, and fits by EM where the step would leave the valid covariance matrices (with few clusters or a small between variance). With missing = "ml", "onestep" instead finds the saturated fit of each replicate by quasi-Newton steps from the moments of the posterior draw, which reach the maximum that the EM finds, and fits by EM where they do not converge. "em" always fits the saturated model by EM, as blavaan does. Ignored for single-level models.

ppp_nsamp

The number of posterior draws, each with one replicate data set, that the PPP of a two-level model uses. Defaults to 250, and is capped at nsamp. Draws that cannot be scored are left out, with a warning. Ignored for single-level models.

wiggle

Equality constraints to relax into approximate ones, as in blavaan. NULL (the default) keeps every equality exact. A character vector. Each entry is a label that the model gives to two or more free parameters (such as a in c(a, a)*x2), or one of the types "loadings", "intercepts" (of observed variables), "means" (of latent variables) and "regressions". A type takes every set of parameters of that type that group.equal or a shared label holds equal. A label that is also a type name is read as the label. In each set, the first parameter in the parameter table (with group.equal, the one of the first group) keeps its prior. Each other parameter becomes a free parameter of its own, with a normal prior centred on the first parameter and with standard deviation wiggle.sd, in place of the equality and of its own prior. Parameters that wiggle does not select stay exactly equal. Variances, covariances, thresholds, a label on parameters of two types (such as a loading and an intercept) and models with composites are not supported. See the section "Approximate equality constraints" of inlavaan().

wiggle.sd

The standard deviation of the normal priors that wiggle sets, on the scale of the parameters. One positive number for all entries of wiggle, or one for each entry, in the same order. The default is 0.1, as in blavaan, and NULL also gives it. wiggle_sd is the same argument. A small value keeps the parameters of a set close together, and a large value lets them differ.

n_qmc

[Deprecated] Has no effect. The VB correction now takes a deterministic step, with no quasi-Monte Carlo nodes.

vb_method

[Deprecated] Has no effect. The VB correction now has one rule, and vb_correction = "full" iterates it.

marginal_correction

[Deprecated] Use marginal_scan. "none" and FALSE are marginal_scan = "plain", which gives the same fit. "shortcut", "shortcut_fd" and "hessian" run marginal_scan = "linear".

samp_copula

[Deprecated] Has no effect. The draws always couple the fitted marginals by a Gaussian copula. With marginal_method = "gaussian" they are the draws of the Laplace approximation.

samp_norta

[Deprecated] Has no effect. The draws no longer adjust the correlations of the copula.

sn_fit_ngrid

[Deprecated] Use control = inlavaan_control(n_grid = ), which gives the same fit.

sn_fit_logthresh

[Deprecated] Use control = inlavaan_control(log_threshold = ), which gives the same fit.

sn_fit_temp

[Deprecated] Has no effect. The skew-normal marginals are fitted with temperature 1.

debug

[Deprecated] Use control = inlavaan_control(debug = TRUE), which gives the same fit.

add_priors

[Deprecated] Use control = inlavaan_control(add_priors = FALSE), which gives the same fit.

optim_method

[Deprecated] Has no effect. The posterior mode is always found by stats::nlminb().

numerical_grad

[Deprecated] Has no effect. The fit always uses the analytic gradient.

hessian_method

[Deprecated] Use control = inlavaan_control(hessian = ), which gives the same fit.

...

Additional arguments to be passed to the lavaan model fitting function.

Details

The acfa() function is a wrapper for the more general inlavaan() function, using the following default arguments:

For further information regarding these arguments, please refer to the lavaan::lavOptions() documentation.

Value

An S4 object of class INLAvaan which is a subclass of the lavaan class.

See Also

Typically, users will interact with the specific latent variable model functions instead, including acfa(), asem(), and agrowth().

Examples

# The famous Holzinger and Swineford (1939) example
HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")

# Fit a CFA model with standardised latent variables
fit <- acfa(HS.model, data = HolzingerSwineford1939, std.lv = TRUE, nsamp = 100)
summary(fit)

Fit an Approximate Bayesian Growth Curve Model

Description

Fit an Approximate Bayesian Growth Curve Model

Usage

agrowth(
  model,
  data = NULL,
  dp = priors_for(),
  test = "standard",
  vb_correction = c("onestep", "full", "none"),
  marginal_method = c("skewnorm", "gaussian"),
  marginal_scan = c("linear", "exact", "laplace", "plain"),
  marginal_laplace_fallback = FALSE,
  nsamp = 1000,
  cov_as_cor = FALSE,
  sn_fit_sample = TRUE,
  control = list(),
  verbose = FALSE,
  silent = FALSE,
  cores = NULL,
  ppp_method = c("onestep", "em"),
  ppp_nsamp = 250L,
  wiggle = NULL,
  wiggle.sd = 0.1,
  n_qmc = NULL,
  vb_method = NULL,
  marginal_correction = NULL,
  samp_copula = NULL,
  samp_norta = NULL,
  sn_fit_ngrid = NULL,
  sn_fit_logthresh = NULL,
  sn_fit_temp = NULL,
  debug = NULL,
  add_priors = NULL,
  optim_method = NULL,
  numerical_grad = NULL,
  hessian_method = NULL,
  ...
)

Arguments

model

A description of the user-specified model. Typically, the model is described using the lavaan model syntax. See model.syntax for more information. Alternatively, a parameter table (e.g., the output of the lavParTable() function) is also accepted.

data

An optional data frame containing the observed variables used in the model. The variables must be continuous: an ordered factor in the model stops the fit, as this version does not fit ordinal or binary indicators (see the section "Ordinal and binary data" of inlavaan()).

dp

Default prior distributions for the different types of model parameters; a named character vector as returned by priors_for(). Types left out take their default priors. A name that is not a type, such as a misspelt one, gives a warning. dp = blavaan::dpriors() works too.

test

Character vector naming the post-estimation quantities to compute and store with the fit. The atoms are "ppp" (posterior predictive p-value), "dic" (deviance information criterion and its pD), "loo" (leave-one-out cross-validation, see loo()) and "waic" (see waic()). Three aliases stand for sets of atoms: "standard" (the default) and its synonym "default" give c("ppp", "dic"); "full" gives all four; "none" gives nothing. Aliases and atoms may be mixed and are unioned, so test = c("standard", "loo") adds the LOO to the default set. The LOO and the WAIC come from one Taylor pass, so asking for either stores both. They run only when asked for, with no time budget. On a model the casewise machinery does not support (a fit with sampling weights) they are skipped with a warning and the rest of the fit proceeds. For a two-level model the PPP follows blavaan: each of ppp_nsamp posterior draws generates replicate data, which are scored against the saturated model (see ppp_method). The two-level PPP is experimental. The fit records what was requested and what was computed (get_inlavaan_internal(fit, "test")); summary(), fitmeasures(), deviance(), logLik() and timing() report only what was computed. add_loo() stores the LOO and WAIC post hoc; loo() and waic() compute on demand. For a random-slope model "ppp" is dropped, with a warning when it was asked for and a message otherwise (see the Random slopes section of inlavaan()). "dic", "loo" and "waic" are unaffected.

vb_correction

The variational Bayes (VB) correction of the posterior mean of the Laplace approximation. "onestep" (default) takes one step from the mode and checks it. Where the check fails, the posterior is far from Gaussian along the step: the fit then solves the VB equation instead, and warns (see diagnostics()). "full" iterates the correction to its fixed point, and "none" leaves it out. The correction moves the marginal log-likelihood, the point at which the DIC is computed, the centre of the LOO and the WAIC, and the Gaussian marginals of marginal_method = "gaussian" and their draws. It does not move the skew-normal marginals or their draws, which are scanned from the mode. The intercepts of a saturated mean structure are the exception: a single-level model of one group with complete data and meanstructure = TRUE, in which every observed variable has a free intercept of its own with a normal prior, and which has no free latent mean, no observed variable in a regression, no equality constraint and no composite. They are not scanned (their nmad in diagnostics() is NA, which is the way to tell): with either marginal_method their marginals are Gaussian and centred at the VB mean. So the correction also moves these marginals, their draws and what is computed from them.

marginal_method

How the marginal posterior of each parameter is approximated. "skewnorm" (default) fits a skew-normal distribution to a scan of the log-posterior along the parameter (see marginal_scan). "gaussian" takes the Gaussian marginal of the Laplace approximation, centred at the VB mean, which is faster. [Deprecated] The old values warn: "marggaus" is the old name of "gaussian", and "asymgaus" now runs "skewnorm". "sampling" is kept for a sampler that is under development, and gives an error.

marginal_scan

How the scan behind each skew-normal marginal is taken. "linear" (default) scans along a straight line through the mode, and adds a linear correction for the changing volume of the other parameters. "exact" computes that volume term exactly at each point of the scan. "laplace" maximises the log-posterior over the other parameters at each point of the scan, and takes the height and the volume there. "plain" adds no volume correction. On the Holzinger and Swineford and the Political Democracy models, "exact" and "laplace" take 10 to 25 times as long as "linear". Ignored with marginal_method = "gaussian", which has no scan.

marginal_laplace_fallback

Logical. Rescan with marginal_scan = "laplace" only the parameters whose ridge bend is above 0.25 (see diagnostics())? Default FALSE, so that a fit costs what marginal_scan says. With TRUE, the parameters where the default scan is likely to give too small a posterior SD get the slower scan, and the others keep the fast one. The column ridge_bend of diagnostics(fit, "param") shows which parameters these are. Ignored with marginal_method = "gaussian" and with marginal_scan = "laplace".

nsamp

The number of samples to draw for all sampling-based approaches (including posterior sampling for model fit indices). A fit that summarises some parameters from the draws needs at least 2: the free covariances and the ⁠:=⁠ and ⁠~*~⁠ parameters. The intercepts that the fit centres have a draw of their own (see centring in inlavaan_control()).

cov_as_cor

Logical. Residual and latent-disturbance covariance parameters (⁠~~⁠ between two observed or two latent variables) are always estimated on the correlation scale internally (an atanh link, the same as for std.ov/std.lv-standardised parameters); by default their reported marginal is then re-derived on the covariance scale \sigma_i \sigma_j \rho from a posterior sample (see nsamp), because that is the scale lavaan/blavaan report by default. When TRUE, that re-derivation is skipped and each such parameter's own directly profiled correlation-scale marginal \rho \in (-1, 1) is reported instead – useful for comparing the profiling machinery (skew-normal fit, VB, ...) against a correlation-scale reference without the sampling/copula step in between. Model estimation is identical either way; only what is reported for these parameters changes. The returned parameter table keeps their covariance classes, so loo() and waic() after the fit score the same model, and the setting is stored as get_inlavaan_internal(fit)$cov_as_cor. The point estimates of these parameters are correlations, so methods that use the point estimates as model parameters (such as fitted() and residuals()) are not meaningful when TRUE. Not the same as lavaan's std.ov/std.lv, which re-parameterises the whole model on a standardised scale. Defaults to FALSE.

sn_fit_sample

Logical. When TRUE (default), a parametric skew-normal is fitted to the posterior samples for covariance and defined parameters. When FALSE, these are summarised using kernel density estimation instead.

control

A list of tuning settings, made by inlavaan_control(), or a plain list with some of its names: the limits of the search for the posterior mode, of the VB correction and of the skew-normal scans, and the settings hessian, debug, add_priors and centring. The defaults suit most fits. An unknown name gives an error. The controls of stats::nlminb() that control took up to INLAvaan 0.3.5, such as iter.max, still work, with a deprecation warning. See inlavaan_control().

verbose

Logical. With FALSE (default) the fit prints one line per stage. With TRUE it also prints the details of each stage of the fit on the internal scale: the start, the mode search, the VB correction and the marginals, with their checks. Use silent = TRUE to print nothing.

silent

Logical. Print nothing at all, and muffle the warnings and messages raised during the fit? Default FALSE. verbose and silent cannot both be TRUE. Errors are still raised. Whether or not silent is TRUE, the texts of the warnings raised during the fit are recorded in the field warnings of get_inlavaan_internal().

cores

A positive whole number or NULL. The number of cores. Other values, such as 0, 2.5 or NA, give an error. With NULL (default), the scans of the skew-normal marginals follow future::plan(), which is serial unless a plan is set, and the LOO and the WAIC asked for in test run serially. With cores > 1, the scans run in parallel when the packages future and parallelly are installed, and serially otherwise. The LOO and the WAIC are then forked via parallel::mclapply() where that is safe, or run over a PSOCK cluster (separate R processes) inside IDE R sessions (RStudio, Positron) and on Windows. 1 is serial.

ppp_method

How the PPP of a two-level model scores the observed and the replicate data against the saturated model. "onestep" (default) takes one Fisher-scoring step from the moments of each posterior draw towards the saturated fit, and fits by EM where the step would leave the valid covariance matrices (with few clusters or a small between variance). With missing = "ml", "onestep" instead finds the saturated fit of each replicate by quasi-Newton steps from the moments of the posterior draw, which reach the maximum that the EM finds, and fits by EM where they do not converge. "em" always fits the saturated model by EM, as blavaan does. Ignored for single-level models.

ppp_nsamp

The number of posterior draws, each with one replicate data set, that the PPP of a two-level model uses. Defaults to 250, and is capped at nsamp. Draws that cannot be scored are left out, with a warning. Ignored for single-level models.

wiggle

Equality constraints to relax into approximate ones, as in blavaan. NULL (the default) keeps every equality exact. A character vector. Each entry is a label that the model gives to two or more free parameters (such as a in c(a, a)*x2), or one of the types "loadings", "intercepts" (of observed variables), "means" (of latent variables) and "regressions". A type takes every set of parameters of that type that group.equal or a shared label holds equal. A label that is also a type name is read as the label. In each set, the first parameter in the parameter table (with group.equal, the one of the first group) keeps its prior. Each other parameter becomes a free parameter of its own, with a normal prior centred on the first parameter and with standard deviation wiggle.sd, in place of the equality and of its own prior. Parameters that wiggle does not select stay exactly equal. Variances, covariances, thresholds, a label on parameters of two types (such as a loading and an intercept) and models with composites are not supported. See the section "Approximate equality constraints" of inlavaan().

wiggle.sd

The standard deviation of the normal priors that wiggle sets, on the scale of the parameters. One positive number for all entries of wiggle, or one for each entry, in the same order. The default is 0.1, as in blavaan, and NULL also gives it. wiggle_sd is the same argument. A small value keeps the parameters of a set close together, and a large value lets them differ.

n_qmc

[Deprecated] Has no effect. The VB correction now takes a deterministic step, with no quasi-Monte Carlo nodes.

vb_method

[Deprecated] Has no effect. The VB correction now has one rule, and vb_correction = "full" iterates it.

marginal_correction

[Deprecated] Use marginal_scan. "none" and FALSE are marginal_scan = "plain", which gives the same fit. "shortcut", "shortcut_fd" and "hessian" run marginal_scan = "linear".

samp_copula

[Deprecated] Has no effect. The draws always couple the fitted marginals by a Gaussian copula. With marginal_method = "gaussian" they are the draws of the Laplace approximation.

samp_norta

[Deprecated] Has no effect. The draws no longer adjust the correlations of the copula.

sn_fit_ngrid

[Deprecated] Use control = inlavaan_control(n_grid = ), which gives the same fit.

sn_fit_logthresh

[Deprecated] Use control = inlavaan_control(log_threshold = ), which gives the same fit.

sn_fit_temp

[Deprecated] Has no effect. The skew-normal marginals are fitted with temperature 1.

debug

[Deprecated] Use control = inlavaan_control(debug = TRUE), which gives the same fit.

add_priors

[Deprecated] Use control = inlavaan_control(add_priors = FALSE), which gives the same fit.

optim_method

[Deprecated] Has no effect. The posterior mode is always found by stats::nlminb().

numerical_grad

[Deprecated] Has no effect. The fit always uses the analytic gradient.

hessian_method

[Deprecated] Use control = inlavaan_control(hessian = ), which gives the same fit.

...

Additional arguments to be passed to the lavaan model fitting function.

Details

The agrowth() function is a wrapper for the more general inlavaan() function, using the following default arguments:

Value

An S4 object of class INLAvaan which is a subclass of the lavaan class.

See Also

Typically, users will interact with the specific latent variable model functions instead, including acfa(), asem(), and agrowth().

Examples

# Linear growth model with a time-varying covariate
mod <- "
  # Intercept and slope with fixed coefficients
    i =~ 1*t1 + 1*t2 + 1*t3 + 1*t4
    s =~ 0*t1 + 1*t2 + 2*t3 + 3*t4

  # (Latent) regressions
    i ~ x1 + x2
    s ~ x1 + x2

  # Time-varying covariates
    t1 ~ c1
    t2 ~ c2
    t3 ~ c3
    t4 ~ c4
"
utils::data("Demo.growth", package = "lavaan")
str(Demo.growth)

fit <- agrowth(mod, data = Demo.growth, nsamp = 100)
summary(fit)

Convert function to single string

Description

Convert function to single string

Usage

as_fun_string(f)

Arguments

f

Function to convert.

Value

A single character vector representing the function.

Examples

f <- function(x) { x^2 + 1 }
as_fun_string(f)

Fit an Approximate Bayesian Structural Equation Model

Description

Fit an Approximate Bayesian Structural Equation Model

Usage

asem(
  model,
  data = NULL,
  dp = priors_for(),
  test = "standard",
  vb_correction = c("onestep", "full", "none"),
  marginal_method = c("skewnorm", "gaussian"),
  marginal_scan = c("linear", "exact", "laplace", "plain"),
  marginal_laplace_fallback = FALSE,
  nsamp = 1000,
  cov_as_cor = FALSE,
  sn_fit_sample = TRUE,
  control = list(),
  verbose = FALSE,
  silent = FALSE,
  cores = NULL,
  ppp_method = c("onestep", "em"),
  ppp_nsamp = 250L,
  wiggle = NULL,
  wiggle.sd = 0.1,
  n_qmc = NULL,
  vb_method = NULL,
  marginal_correction = NULL,
  samp_copula = NULL,
  samp_norta = NULL,
  sn_fit_ngrid = NULL,
  sn_fit_logthresh = NULL,
  sn_fit_temp = NULL,
  debug = NULL,
  add_priors = NULL,
  optim_method = NULL,
  numerical_grad = NULL,
  hessian_method = NULL,
  ...
)

Arguments

model

A description of the user-specified model. Typically, the model is described using the lavaan model syntax. See model.syntax for more information. Alternatively, a parameter table (e.g., the output of the lavParTable() function) is also accepted.

data

An optional data frame containing the observed variables used in the model. The variables must be continuous: an ordered factor in the model stops the fit, as this version does not fit ordinal or binary indicators (see the section "Ordinal and binary data" of inlavaan()).

dp

Default prior distributions for the different types of model parameters; a named character vector as returned by priors_for(). Types left out take their default priors. A name that is not a type, such as a misspelt one, gives a warning. dp = blavaan::dpriors() works too.

test

Character vector naming the post-estimation quantities to compute and store with the fit. The atoms are "ppp" (posterior predictive p-value), "dic" (deviance information criterion and its pD), "loo" (leave-one-out cross-validation, see loo()) and "waic" (see waic()). Three aliases stand for sets of atoms: "standard" (the default) and its synonym "default" give c("ppp", "dic"); "full" gives all four; "none" gives nothing. Aliases and atoms may be mixed and are unioned, so test = c("standard", "loo") adds the LOO to the default set. The LOO and the WAIC come from one Taylor pass, so asking for either stores both. They run only when asked for, with no time budget. On a model the casewise machinery does not support (a fit with sampling weights) they are skipped with a warning and the rest of the fit proceeds. For a two-level model the PPP follows blavaan: each of ppp_nsamp posterior draws generates replicate data, which are scored against the saturated model (see ppp_method). The two-level PPP is experimental. The fit records what was requested and what was computed (get_inlavaan_internal(fit, "test")); summary(), fitmeasures(), deviance(), logLik() and timing() report only what was computed. add_loo() stores the LOO and WAIC post hoc; loo() and waic() compute on demand. For a random-slope model "ppp" is dropped, with a warning when it was asked for and a message otherwise (see the Random slopes section of inlavaan()). "dic", "loo" and "waic" are unaffected.

vb_correction

The variational Bayes (VB) correction of the posterior mean of the Laplace approximation. "onestep" (default) takes one step from the mode and checks it. Where the check fails, the posterior is far from Gaussian along the step: the fit then solves the VB equation instead, and warns (see diagnostics()). "full" iterates the correction to its fixed point, and "none" leaves it out. The correction moves the marginal log-likelihood, the point at which the DIC is computed, the centre of the LOO and the WAIC, and the Gaussian marginals of marginal_method = "gaussian" and their draws. It does not move the skew-normal marginals or their draws, which are scanned from the mode. The intercepts of a saturated mean structure are the exception: a single-level model of one group with complete data and meanstructure = TRUE, in which every observed variable has a free intercept of its own with a normal prior, and which has no free latent mean, no observed variable in a regression, no equality constraint and no composite. They are not scanned (their nmad in diagnostics() is NA, which is the way to tell): with either marginal_method their marginals are Gaussian and centred at the VB mean. So the correction also moves these marginals, their draws and what is computed from them.

marginal_method

How the marginal posterior of each parameter is approximated. "skewnorm" (default) fits a skew-normal distribution to a scan of the log-posterior along the parameter (see marginal_scan). "gaussian" takes the Gaussian marginal of the Laplace approximation, centred at the VB mean, which is faster. [Deprecated] The old values warn: "marggaus" is the old name of "gaussian", and "asymgaus" now runs "skewnorm". "sampling" is kept for a sampler that is under development, and gives an error.

marginal_scan

How the scan behind each skew-normal marginal is taken. "linear" (default) scans along a straight line through the mode, and adds a linear correction for the changing volume of the other parameters. "exact" computes that volume term exactly at each point of the scan. "laplace" maximises the log-posterior over the other parameters at each point of the scan, and takes the height and the volume there. "plain" adds no volume correction. On the Holzinger and Swineford and the Political Democracy models, "exact" and "laplace" take 10 to 25 times as long as "linear". Ignored with marginal_method = "gaussian", which has no scan.

marginal_laplace_fallback

Logical. Rescan with marginal_scan = "laplace" only the parameters whose ridge bend is above 0.25 (see diagnostics())? Default FALSE, so that a fit costs what marginal_scan says. With TRUE, the parameters where the default scan is likely to give too small a posterior SD get the slower scan, and the others keep the fast one. The column ridge_bend of diagnostics(fit, "param") shows which parameters these are. Ignored with marginal_method = "gaussian" and with marginal_scan = "laplace".

nsamp

The number of samples to draw for all sampling-based approaches (including posterior sampling for model fit indices). A fit that summarises some parameters from the draws needs at least 2: the free covariances and the ⁠:=⁠ and ⁠~*~⁠ parameters. The intercepts that the fit centres have a draw of their own (see centring in inlavaan_control()).

cov_as_cor

Logical. Residual and latent-disturbance covariance parameters (⁠~~⁠ between two observed or two latent variables) are always estimated on the correlation scale internally (an atanh link, the same as for std.ov/std.lv-standardised parameters); by default their reported marginal is then re-derived on the covariance scale \sigma_i \sigma_j \rho from a posterior sample (see nsamp), because that is the scale lavaan/blavaan report by default. When TRUE, that re-derivation is skipped and each such parameter's own directly profiled correlation-scale marginal \rho \in (-1, 1) is reported instead – useful for comparing the profiling machinery (skew-normal fit, VB, ...) against a correlation-scale reference without the sampling/copula step in between. Model estimation is identical either way; only what is reported for these parameters changes. The returned parameter table keeps their covariance classes, so loo() and waic() after the fit score the same model, and the setting is stored as get_inlavaan_internal(fit)$cov_as_cor. The point estimates of these parameters are correlations, so methods that use the point estimates as model parameters (such as fitted() and residuals()) are not meaningful when TRUE. Not the same as lavaan's std.ov/std.lv, which re-parameterises the whole model on a standardised scale. Defaults to FALSE.

sn_fit_sample

Logical. When TRUE (default), a parametric skew-normal is fitted to the posterior samples for covariance and defined parameters. When FALSE, these are summarised using kernel density estimation instead.

control

A list of tuning settings, made by inlavaan_control(), or a plain list with some of its names: the limits of the search for the posterior mode, of the VB correction and of the skew-normal scans, and the settings hessian, debug, add_priors and centring. The defaults suit most fits. An unknown name gives an error. The controls of stats::nlminb() that control took up to INLAvaan 0.3.5, such as iter.max, still work, with a deprecation warning. See inlavaan_control().

verbose

Logical. With FALSE (default) the fit prints one line per stage. With TRUE it also prints the details of each stage of the fit on the internal scale: the start, the mode search, the VB correction and the marginals, with their checks. Use silent = TRUE to print nothing.

silent

Logical. Print nothing at all, and muffle the warnings and messages raised during the fit? Default FALSE. verbose and silent cannot both be TRUE. Errors are still raised. Whether or not silent is TRUE, the texts of the warnings raised during the fit are recorded in the field warnings of get_inlavaan_internal().

cores

A positive whole number or NULL. The number of cores. Other values, such as 0, 2.5 or NA, give an error. With NULL (default), the scans of the skew-normal marginals follow future::plan(), which is serial unless a plan is set, and the LOO and the WAIC asked for in test run serially. With cores > 1, the scans run in parallel when the packages future and parallelly are installed, and serially otherwise. The LOO and the WAIC are then forked via parallel::mclapply() where that is safe, or run over a PSOCK cluster (separate R processes) inside IDE R sessions (RStudio, Positron) and on Windows. 1 is serial.

ppp_method

How the PPP of a two-level model scores the observed and the replicate data against the saturated model. "onestep" (default) takes one Fisher-scoring step from the moments of each posterior draw towards the saturated fit, and fits by EM where the step would leave the valid covariance matrices (with few clusters or a small between variance). With missing = "ml", "onestep" instead finds the saturated fit of each replicate by quasi-Newton steps from the moments of the posterior draw, which reach the maximum that the EM finds, and fits by EM where they do not converge. "em" always fits the saturated model by EM, as blavaan does. Ignored for single-level models.

ppp_nsamp

The number of posterior draws, each with one replicate data set, that the PPP of a two-level model uses. Defaults to 250, and is capped at nsamp. Draws that cannot be scored are left out, with a warning. Ignored for single-level models.

wiggle

Equality constraints to relax into approximate ones, as in blavaan. NULL (the default) keeps every equality exact. A character vector. Each entry is a label that the model gives to two or more free parameters (such as a in c(a, a)*x2), or one of the types "loadings", "intercepts" (of observed variables), "means" (of latent variables) and "regressions". A type takes every set of parameters of that type that group.equal or a shared label holds equal. A label that is also a type name is read as the label. In each set, the first parameter in the parameter table (with group.equal, the one of the first group) keeps its prior. Each other parameter becomes a free parameter of its own, with a normal prior centred on the first parameter and with standard deviation wiggle.sd, in place of the equality and of its own prior. Parameters that wiggle does not select stay exactly equal. Variances, covariances, thresholds, a label on parameters of two types (such as a loading and an intercept) and models with composites are not supported. See the section "Approximate equality constraints" of inlavaan().

wiggle.sd

The standard deviation of the normal priors that wiggle sets, on the scale of the parameters. One positive number for all entries of wiggle, or one for each entry, in the same order. The default is 0.1, as in blavaan, and NULL also gives it. wiggle_sd is the same argument. A small value keeps the parameters of a set close together, and a large value lets them differ.

n_qmc

[Deprecated] Has no effect. The VB correction now takes a deterministic step, with no quasi-Monte Carlo nodes.

vb_method

[Deprecated] Has no effect. The VB correction now has one rule, and vb_correction = "full" iterates it.

marginal_correction

[Deprecated] Use marginal_scan. "none" and FALSE are marginal_scan = "plain", which gives the same fit. "shortcut", "shortcut_fd" and "hessian" run marginal_scan = "linear".

samp_copula

[Deprecated] Has no effect. The draws always couple the fitted marginals by a Gaussian copula. With marginal_method = "gaussian" they are the draws of the Laplace approximation.

samp_norta

[Deprecated] Has no effect. The draws no longer adjust the correlations of the copula.

sn_fit_ngrid

[Deprecated] Use control = inlavaan_control(n_grid = ), which gives the same fit.

sn_fit_logthresh

[Deprecated] Use control = inlavaan_control(log_threshold = ), which gives the same fit.

sn_fit_temp

[Deprecated] Has no effect. The skew-normal marginals are fitted with temperature 1.

debug

[Deprecated] Use control = inlavaan_control(debug = TRUE), which gives the same fit.

add_priors

[Deprecated] Use control = inlavaan_control(add_priors = FALSE), which gives the same fit.

optim_method

[Deprecated] Has no effect. The posterior mode is always found by stats::nlminb().

numerical_grad

[Deprecated] Has no effect. The fit always uses the analytic gradient.

hessian_method

[Deprecated] Use control = inlavaan_control(hessian = ), which gives the same fit.

...

Additional arguments to be passed to the lavaan model fitting function.

Details

The asem() function is a wrapper for the more general inlavaan() function, using the following default arguments:

For further information regarding these arguments, please refer to the lavaan::lavOptions() documentation.

Value

An S4 object of class INLAvaan which is a subclass of the lavaan class.

See Also

Typically, users will interact with the specific latent variable model functions instead, including acfa(), asem(), and agrowth().

Examples

# The industrialization and Political Democracy Example from Bollen (1989), page
# 332
model <- "
  # Latent variable definitions
     ind60 =~ x1 + x2 + x3
     dem60 =~ y1 + a*y2 + b*y3 + c*y4
     dem65 =~ y5 + a*y6 + b*y7 + c*y8

  # (Latent) regressions
    dem60 ~ ind60
    dem65 ~ ind60 + dem60

  # Residual correlations
    y1 ~~ y5
    y2 ~~ y4 + y6
    y3 ~~ y7
    y4 ~~ y8
    y6 ~~ y8
"
utils::data("PoliticalDemocracy", package = "lavaan")

fit <- asem(model, PoliticalDemocracy, test = "none")
summary(fit)

Bayesian Fit Indices

Description

Compute posterior distributions of Bayesian fit indices for an INLAvaan model, analogous to blavaan::blavFitIndices().

Usage

bfit_indices(
  object,
  baseline.model = NULL,
  rescale = c("devM", "MCMC"),
  nsamp = NULL,
  samp_copula = NULL
)

## S3 method for class 'bfit_indices'
summary(object, ...)

## S3 method for class 'bfit_indices_summary'
print(x, ..., nd = 3L)

## S3 method for class 'bfit_indices'
print(x, ...)

Arguments

object

An object of class INLAvaan.

baseline.model

The baseline (null) model that the incremental fit indices (BCFI, BTLI, BNFI) are scaled against. NULL (default) fits the independence model on the same data and options automatically, as lavaan does: every observed variable keeps its variance (and intercept) and nothing correlates. That fit uses the default priors, Gaussian marginals and no VB correction, since only its posterior draws and pD are needed. It is fitted at the first call and kept with object, so later calls (and fitmeasures()) reuse it and their incremental indices are the same. Supply an INLAvaan object to use another baseline, or FALSE to skip the incremental indices.

rescale

Character string controlling how the Bayesian chi-square is rescaled. "devM" (default) subtracts pD from the deviance at each sample. "MCMC" uses the classical chi-square and classical df at each sample.

nsamp

Number of posterior samples, by default the number of draws of the fit. The fit keeps the log-likelihood of each of its draws with its DIC, so up to that number the indices use the first nsamp draws of the fit: nothing is drawn or scored again, and the absolute indices do not depend on the random seed. The independence baseline is used the same way. A larger value draws that many new samples.

samp_copula

[Deprecated] Has no effect. The draws always couple the fitted marginals by a Gaussian copula, as the draws of the fit do.

...

Additional arguments passed to methods.

x

An object of class bfit_indices, or the table that summary() returns for one (for print).

nd

Number of decimals in the printed summary table.

Details

For a random-slope model, which has no saturated model, the chi-square and the number of sample moments come from the unrestricted random-coefficient model with the same random-effects design, fitted by maximum likelihood. This reference is INLAvaan's own construction. It is available on the closed-form route only, for models without between-only outcomes, and needs enough clusters for its parameters.

A posterior draw whose log-likelihood cannot be computed, usually because its implied covariance matrix is not positive definite, has no chi-square. Its fit indices are NA, the summaries leave it out, and a warning says how many draws were left out. The PPP and the DIC leave out such draws too.

The degrees of freedom are df = p - p_D, where p is the number of sample moments and p_D the effective number of parameters: the p_D of the DIC with rescale = "devM" (the number of free parameters when it is not between 0 and p), and the number of free parameters with rescale = "MCMC". When df is not positive, as for a just-identified model with rescale = "MCMC" (with "devM" such a model can still have p_D < p), or for a model with many approximate equalities (wiggle in inlavaan()), some indices are not defined, and a warning of class inlavaan_bfit_df names them. At df \le 0 the absolute indices (BRMSEA, BGammaHat, adjBGammaHat and BMc) are left out, and BTLI, which divides by df, is NA. At df < 0 BCFI is NA too, since each draw then adds -df to its noncentrality. BNFI does not use df and is kept. blavaan computes every index, and warns at df < 0.

Value

An S3 object of class "bfit_indices" containing:

indices

Named list of numeric vectors (one per posterior sample) for each computed fit index.

details

List with chisq (per-sample deviance, NA for a draw that could not be scored), df, pD, rescale, and nsamp.

Use summary() to obtain a table of posterior summaries (Mean, SD, quantiles, Mode) for each index.

See Also

lavaan::fitMeasures(), blavaan::blavFitIndices(), fitmeasures(), compare()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            silent = TRUE)

# Absolute fit indices
bf <- bfit_indices(fit)
bf
summary(bf)



Compare Bayesian Models Fitted with INLAvaan

Description

Compare two or more Bayesian SEM fitted with INLAvaan, reporting model-fit statistics and (optionally) fit indices side by side.

Usage

compare(x, y, ..., fit.measures = NULL, loo = FALSE)

## S4 method for signature 'INLAvaan'
compare(x, y, ..., fit.measures = NULL, loo = FALSE)

## S4 method for signature 'INLAvaan'
anova(object, ...)

Arguments

x, y, ...

Two or more INLAvaan (or inlavaan_internal) objects fitted to the same data.

fit.measures

Character vector of additional fit-measure names to include (e.g. "BRMSEA", "BCFI"). Use "all" to include every measure returned by fitMeasures(). The default (NULL) shows only the core comparison statistics.

loo

Logical; if TRUE, compare models by leave-one-out cross-validation with paired standard errors (see Details). Defaults to FALSE.

object

An INLAvaan object (the anova() method, which is disabled and redirects to compare()).

Details

All models appear in the comparison table. When incremental fit indices (BCFI, BTLI, BNFI) are requested via fit.measures, they are scaled against the independence (null) model, fitted once on the data of the first model and shared by every model in the table (see bfit_indices()).

The default table always includes:

Fit all models with the same vb_correction setting. compare() warns when they differ.

The marginal log-likelihood normalises each prior on its own range, and does not divide by the prior probability that the model-implied covariance matrix is positive definite. The estimates do not depend on this constant, but a Bayes factor between models with different covariance structures leaves out the difference of their constants. Merkle et al. (2023) call a prior that the positive definite requirement changes in this way opaque, and show its effect on a Bayes factor.

Marginal likelihoods, Bayes factors and DIC of fits with composites (⁠<~⁠) treat the indicator (co)variances that lavaan fixes at their sample values as known, so compare() warns unless all models fix the same ones. The LOO comparison (loo = TRUE) remains valid across such models.

Set fit.measures to a character vector of measure names (anything returned by fitMeasures()) to append extra columns. Use fit.measures = "all" to include every available measure. For a fit that loo() refuses because of its sampling weights, a LOO or WAIC measure asked for in fit.measures is NA, with a warning.

Set loo = TRUE to compare models by leave-one-out cross-validation (see loo()). This appends ELPD / SE (the Taylor expected log predictive density and its standard error), p_loo, and, against the best-ELPD model, the difference elpd_diff with its paired standard error se_diff computed from the pointwise contributions (the appropriate uncertainty for nested or same-data comparisons). Every model is scored at one common Taylor order, the lowest any of them can supply: if some unit of some model has no second-order term, all models are compared at first order, since otherwise a change of estimator between models would read as a difference between the models themselves. The order used is stated when the table is printed. The table is then sorted by descending ELPD. All models must be fitted to the same data with matching units; units are paired by id rather than by row order, so fits that stack groups differently – a pooled fit against a multigroup fit, or multigroup fits with different group orderings – still pair up unit by unit. For missing-data (FIML) fits, "the same data" also means the same observed entries: each unit is scored on the entries it has, so comparisons require identical missingness patterns across models. All models must also share the score flavour (see loo()): mixing fits with modelled covariates (fixed.x = FALSE, joint scores) and fixed covariates (fixed.x = TRUE, conditional scores) is refused. Joint scores additionally require identical variable sets across models, while conditional scores require only matching outcome variables – covariate sets may differ, which is the covariate-selection setting. Stored LOO results (test including "loo" or "full", or add_loo()) are reused. A fit that loo() refuses, such as one with sampling weights, is refused here too.

compare() warns when the models do not score the same variables, for instance when a variable is a covariate in one model and an outcome in another, or when the models differ in fixed.x. Their covariates may differ.

When any of the models has random slopes (lavaan's rv() modifier; see inlavaan()), compare() aborts unless all the models were fitted with fixed.x = TRUE, score the same outcome variables, and share one integration.ngh on the quadrature route. Their covariates may differ. The fixed-slope model (the same path without rv()) is a valid comparator for testing a random slope.

anova() is disabled for INLAvaan fits – there is no direct Bayesian analogue of the classical likelihood-ratio test – and points here instead.

Value

A data frame of class compare.inlavaan_internal containing model fit statistics, sorted by descending marginal log-likelihood (or by descending ELPD when loo = TRUE).

References

https://lavaan.ugent.be/tutorial/groups.html

Merkle, E. C., Ariyo, O., Winter, S. D., & Garnier-Villarreal, M. (2023). Opaque prior distributions in Bayesian latent variable models. Methodology, 19(3), 228–255. doi:10.5964/meth.11167

See Also

fitmeasures(), bfit_indices()

Examples


# Model comparison on multigroup analysis (measurement invariance)
HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")

# Configural invariance
fit1 <- acfa(HS.model, data = HolzingerSwineford1939, group = "school")

# Weak invariance
fit2 <- acfa(
  HS.model,
  data = HolzingerSwineford1939,
  group = "school",
  group.equal = "loadings"
)

# Strong invariance
fit3 <- acfa(
  HS.model,
  data = HolzingerSwineford1939,
  group = "school",
  group.equal = c("intercepts", "loadings")
)

# Compare models (fit1 = configural = baseline, always first argument)
compare(fit1, fit2, fit3)

# With extra fit measures
compare(fit1, fit2, fit.measures = c("BRMSEA", "BMc"))

# With incremental indices (baseline = fit1, passed to fitMeasures())
compare(fit1, fit2, fit3, fit.measures = c("BCFI", "BTLI"))


Density of a Beta distribution on a bounded interval

Description

Density of a Beta distribution on a bounded interval

Usage

dbeta_box(x, shape1, shape2, a, b, log = FALSE)

Arguments

x

A numeric vector of quantiles.

shape1, shape2

non-negative parameters of the Beta distribution.

a

The lower bound of the interval.

b

The upper bound of the interval.

log

Logical; if TRUE, probabilities p are given as log(p).

Value

A numeric vector of density values.

Examples

# Beta(2,5) on (0,100)
x <- seq(0, 100, length.out = 100)
y <- dbeta_box(x, shape1 = 2, shape2 = 5, a = 0, b = 100)
plot(x, y, type = "l", main = "Beta(2,5) on (0,100)")

# Beta(1,1) i.e. uniform on (-1, 1)
x <- seq(-1, 1, length.out = 100)
y <- dbeta_box(x, shape1 = 1, shape2 = 1, a = -1, b = 1)
plot(x, y, type = "l", main = "Beta(1,1) on (-1,1)")

Deviance for INLAvaan Models

Description

Extract the (Bayesian) deviance of a fitted INLAvaan model. Unlike lavaan, which has no deviance() method, this follows the BUGS/JAGS/Stan convention: "deviance" is -2 times the log-likelihood, summarised over the posterior.

Usage

## S3 method for class 'INLAvaan'
deviance(object, type = c("mean", "plugin"), ...)

Arguments

object

An object of class INLAvaan.

type

Character. "mean" (default) returns the posterior mean deviance \bar{D} = E[-2\log p(y \mid \theta)], averaged over posterior draws. "plugin" returns the deviance evaluated at the centre of the posterior approximation, \hat{D} = -2\log p(y \mid \hat\theta) (matching -2 * logLik(object, type = "plugin")). INLAvaan approximates the posterior on a transformed scale (variances on the log scale, for example), and \hat\theta is the mean after the VB correction on that scale, or the mode with vb_correction = "none", mapped back to the model parameters. It is close to the posterior means that coef(object) returns, but it is not the same point. Both require the model to have been fitted with a test that includes "dic" (the default "standard" does).

...

Currently unused.

Details

\bar{D} and \hat{D} are the two ingredients of the Deviance Information Criterion, DIC = \bar{D} + p_D where p_D = \bar{D} - \hat{D} is the effective number of parameters. Use compare() to compare models by DIC (or Bayes factors, or LOO/WAIC) rather than comparing raw deviances directly.

This p_D is estimated from the posterior draws. loo() reaches the same quantity in closed form as pd_trace, the trace \mathrm{tr}(\Sigma \mathcal{I}); the two routes estimate one target but do not agree exactly in a finite sample. Neither is p_loo, which estimates something else entirely (see loo()).

Value

A length-one numeric of class inlavaan_deviance, with the effective number of parameters (pD) and DIC attached as attributes.

See Also

logLik(), compare()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "standard", silent = TRUE)

deviance(fit)
attr(deviance(fit), "DIC")



Convergence and Approximation Diagnostics for INLAvaan Models

Description

Extract convergence and approximation-quality diagnostics from a fitted INLAvaan model.

Usage

diagnostics(object, ...)

## S4 method for signature 'INLAvaan'
diagnostics(object, type = c("global", "param"), ...)

Arguments

object

An object of class INLAvaan.

...

Currently unused.

type

Character. "global" (default) returns a named numeric vector of scalar diagnostics. "param" returns a data frame with one row per free parameter containing per-parameter diagnostics. An intercept that the fit centres is described in its centred coordinate (see centring in inlavaan_control()).

Details

The diagnostics are those of the engine that fits the model (the files of inlavanilla that INLAvaan copies), in its order and under its names. Then come the diagnostics that INLAvaan adds for structural equation models, and last the names that INLAvaan 0.4.0 deprecates. Read the values by name, not by position. A posterior SD here is the Laplace SD at the mode, s_j, the square root of the diagonal of \Omega, the covariance matrix of the Laplace approximation. Values that a fit did not compute are NA: the VB quantities with vb_correction = "none", and the scan quantities with Gaussian marginals (marginal_method = "gaussian") and for the intercepts of a saturated mean structure, whose marginals are Gaussian, centred at the VB mean, and have no scan. The mean_gap of such an intercept is NA too: its marginal is only as accurate as the VB correction, and no scan checks its centre.

Global diagnostics (type = "global"):

npar

Number of free parameters.

converged

1 if the optimiser converged, 0 otherwise.

iterations

Number of optimiser iterations. When the gradient at the first mode is too large, the optimiser runs again from there, and this is the total of both runs.

grad_inf

L-infinity norm of the analytic gradient at the mode (max |grad|). Should be ~0 at convergence.

grad_inf_rel

Relative L-infinity norm of the analytic gradient (max |grad| / (|par| + 1e-6)).

grad_l2

L2 (Euclidean) norm of the analytic gradient at the mode.

mode_shift_max

Maximum, across parameters, of the Newton step at the reported mode in posterior-SD units (max |\Omega grad| / s). Unlike the raw gradient norms this is scale-free: it estimates how far the reported mode sits from the true posterior mode relative to the posterior uncertainty. Should be ~0 at convergence.

hess_cond

Condition number of the Hessian at the mode, the ratio of the largest to the smallest eigenvalue of \Omega. It depends on the units of the parameters.

hess_cond_cor

The same for the posterior correlation matrix, with each parameter in its own posterior-SD units, so it is free of units. Large values mean that some combination of the parameters is weakly identified. The fit-time check reads this one.

vb_applied

1 if VB correction was applied, 0 otherwise.

vb_shift_max

Maximum, across parameters, of the absolute VB correction in posterior-SD units (max |vb_shift_sigma|).

vb_kld_global

KL divergence between the Laplace Gaussian and its VB-shifted copy, \frac12 \delta^\top \Omega^{-1} \delta, which is also the VB term of the marginal log-likelihood.

kld_max

Maximum per-parameter KL divergence from the VB correction.

kld_mean

Mean per-parameter KL divergence.

nmad_max

Maximum normalised max-absolute-deviation across the scanned marginals.

nmad_mean

Mean NMAD across the scanned marginals.

unscanned_mass_max

Maximum, across parameters, of unscanned_mass (see below). Before INLAvaan 0.4.0 it was scan_end_mass_max.

grad_gap_max

Maximum grad_gap (see below). Should be ~0.

vb_fallback

1 if the VB correction handed over to its fallback optimiser, 0 otherwise. It is recorded only: the fallback is a route of the solver, and the other VB checks judge where it lands.

vb_step_max

Maximum vb_step_sigma (see below).

vb_lhat, vb_j0, vb_j1

The check of the one-step VB correction, from a second pass of its rule at the step. The step is the first iterate of a fixed-point map whose fixed point is the VB mean, and it is close to that mean only where the map is a contraction. vb_lhat is the size of the residual of the VB equation at the step over its size at the mode. vb_j0 and vb_j1 are the slope of the map along the step, at the mode and at the step. The check passes when vb_lhat is below 1 and both slopes lie between -1 and 1, and a value that is not finite fails it. NA with vb_correction = "full", and when the step was below vb_tol (see inlavaan_control()) in every parameter, which is too small to check.

vb_solve

1 if the check of the one-step VB correction failed, 0 if it passed, NA if it did not run. After a failed check the fit solves the VB equation instead, from the mode, at no more cost than the search for the mode and the Hessian took, and the fit-time warning says that the posterior is far from Gaussian along the mean correction (see below). summary() then gives the VB correction as ONESTEP+SOLVE.

mean_gap_max

Maximum, across parameters, of |mean_gap| (see below).

ridge_bend_max

Maximum ridge_bend (see below).

n_heavy_tails

Number of marginals with heavy tails, those whose tails is FALSE.

nsamp

Number of posterior samples drawn.

psi_npd_share

Share of the posterior draws in which the covariance matrix of the latent variables (psi) of some block is not positive definite. Each correlation is kept in (-1, 1) on its own, but a block of several free correlations can still leave the matrix indefinite, and the likelihood guards only the model-implied covariance matrix. Zero when no psi matrix has a free covariance.

theta_npd_share

The same share for the residual covariance matrix of the observed variables (theta).

vb_mcse_max, vb_mcse_mean

Deprecated, and always NA: the VB correction uses a deterministic rule, which has no quadrature error. They will be removed in INLAvaan 0.5.0.

Per-parameter diagnostics (type = "param"): A data frame with columns:

names

Parameter name.

grad

Analytic gradient of the negative log-posterior at the mode. Should be ~0 at convergence.

grad_abs

Absolute analytic gradient.

grad_rel

Relative analytic gradient |grad| / (|par| + 1e-6), with par the posterior mean on the internal scale.

mode_shift_sigma

Newton step at the reported mode in posterior-SD units. Should be ~0 at convergence.

kld

KL divergence between the Laplace Gaussian marginal and its VB-shifted copy, vb_shift_sigma^2 / 2.

vb_shift

VB correction shift (on the internal scale).

vb_shift_sigma

VB shift in units of posterior SD.

nmad

Normalised max-absolute-deviation of the skew-normal fit from the scanned posterior.

alpha

Shape parameter of the fitted skew-normal marginal, on the internal scale. Zero is a Gaussian marginal, and the sign gives the direction of the skew.

unscanned_mass

Mass the fitted marginal puts outside the window that was scanned to fit it, F(\hat\theta_j - 4 s_j) + 1 - F(\hat\theta_j + 4 s_j), where F is the fitted skew-normal distribution function and \hat\theta_j the posterior mode. The marginal is fitted inside that window only, so mass outside it is extrapolation, and when this is large the 2.5\ A Gaussian marginal gives 2\Phi(-4) = 6.3e-05, and healthy fits sit between 1e-03 and 1e-02. Before INLAvaan 0.4.0 it was scan_end_mass.

grad_gap

How far the analytic gradient is from central differences of the log-posterior at the mode: the larger of the gap in slope per conditional posterior SD (about how far a wrong gradient moves the mode, in posterior SDs) and half the relative gap in curvature (about the relative error it makes in a posterior SD). Should be ~0.

vb_step_sigma

The step still to go at the VB mean, in posterior-SD units, as mode_shift_sigma is for the mode. NA after the default one-step VB correction when its check passed. When the check failed (vb_solve), it is the step still to go where the solve stopped: at vb_tol, at vb_maxit or at the cap on its cost that vb_budget sets (see inlavaan_control()). It is then not a check of its own, but the bullet on the failed check says how far the solve stopped short when it is above 0.1. With vb_budget = 0 the fit stays at the mode, and it is the first step of the fixed-point rule from the mode. That step can be much larger than the distance from the mode to the VB mean, so it then overstates how far the solve stopped short.

mean_gap

Gap between the mean of the skew-normal marginal and the VB mean, in posterior-SD units. Both estimate the shift from the mode to the posterior mean, so a large gap says that the posterior is far from Gaussian along this parameter.

gamma1

The volume correction of the scan: the slope, per posterior SD, added to the scanned log-posterior for the changing volume of the other parameters.

tails

FALSE when the density at an end of the scan is still above 5\ skew-normal extrapolates it.

ridge_bend

The log-density, in nats, that the straight scan misses at 2 posterior SDs either side of the mode, where the ridge of high posterior density bends away from it. A large value means that the marginal may be too narrow: 0.25 is a posterior SD about 10\ small. Above 1 the fit-time warning names the parameter (see below). With marginal_scan = "laplace" the scan follows the ridge, and the value is reported but not flagged.

grad_num, grad_diff, vb_mcse_sigma

Deprecated, and always NA: grad_gap checks the analytic gradient in place of grad_num and grad_diff, and the VB shift has no quadrature error. They will be removed in INLAvaan 0.5.0.

Fit-time warnings: inlavaan() runs these checks once at the end of every fit and emits a single consolidated warning (condition class "inlavaan_diagnostics_warning") when any of them looks off:

When the optimiser did not converge, the warning says what to try: to raise mode_maxit or mode_maxeval in inlavaan_control() when it stopped at one of these limits, and other starting values otherwise. When mode_shift_max is above 1, or a marginal puts more than 0.9 of its mass outside its scan, the warning also says that the mode may be far from the posterior mass. When the VB correction did not converge, or shifted a parameter by more than 1 posterior SD, in a fit with skew-normal marginals and the intercepts of a saturated mean structure, the warning also says that the Gaussian marginals of those intercepts are centred on the VB mean. After a failed one-step check it lists their posterior means with what else to treat with care. Each of the two names only the intercepts whose own VB shift, or step still to go, is over 0.1 posterior SDs, and says nothing of the intercepts when there are none. The mean gap never warns. Three of these checks have calibration behind them. Over 1,046 simulated fits with MCMC references, the Spearman correlation with the worst-case posterior-mean discrepancy was 0.64 for the VB shift in SD units, 0.59 for the unscanned mass and 0.48 for the NMAD. The other checks are rules of thumb. Every number above is a package default, chosen so that a healthy fit stays silent, and not a calibrated cut-off: a tripped check is a prompt to look again, and silence is not a certificate of accuracy. Silence the check with suppressWarnings(), or selectively by handling the condition class.

Checks of the model: inlavaan() also runs three checks that are about the model and the data, not the approximation, and emits them in a warning of their own (condition class "inlavaan_model_warning"):

On a study of 58 models (textbook models and a zoo of harder cases), no healthy fit raised any of the three. The levels are package defaults, not calibrated cut-offs.

Value

For type = "global", a named numeric vector (class "diagnostics.INLAvaan"). For type = "param", a data frame (class c("diagnostics.INLAvaan.param", "data.frame")).

See Also

timing(), fitmeasures(), plot()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "none", silent = TRUE)

# Global convergence summary
diagnostics(fit)

# Per-parameter table
diagnostics(fit, type = "param")



The skew-normal distribution

Description

Density, distribution function and quantile function of the skew-normal distribution with location xi, scale omega and shape alpha, whose density is

f(x) = \frac{2}{\omega} \phi(z) \Phi(\alpha z), \quad z = (x - \xi) / \omega.

Usage

dsnorm(x, xi, omega, alpha, logC = 0, log = FALSE)

psnorm(q, xi = 0, omega = 1, alpha = 0, lower_tail = TRUE)

qsnorm(p, xi = 0, omega = 1, alpha = 0)

Arguments

x, q

Vector of quantiles.

p

Vector of probabilities.

xi

Location parameter.

omega

Scale parameter, positive.

alpha

Shape parameter. alpha = 0 gives the normal distribution.

logC

Log-constant added to the log density, so that the density is multiplied by exp(logC).

log

Logical; if TRUE, dsnorm() returns the log density.

lower_tail

Logical; if TRUE (default), probabilities are P(X \le q), otherwise P(X > q).

Details

psnorm() computes F(q) = \Phi(z) - 2 T(z, \alpha) with Owen's T function by 48-point Gauss-Legendre quadrature, to an absolute error of about 2e-16. The upper tail is computed by reflection, so a small probability in the heavy tail (the upper tail when alpha > 0, the lower tail when alpha < 0) keeps its relative accuracy. In the light tail (the upper tail when alpha < 0, the lower tail when alpha > 0), the value is accurate only in absolute terms: a probability near 1e-12 there can have a relative error of about 1e-4, and a probability below about 1e-17 can come out as 0.

qsnorm() starts from qsnorm_fast() and refines the quantile by Newton's method on the log of the smaller tail probability, which keeps quantiles far out in the tails accurate. Where the smaller tail probability is 1e-6 or more, psnorm(qsnorm(p)) returns p to a relative error of about 1e-10. Further out in the light tail, psnorm() loses relative accuracy to cancellation, so qsnorm() computes that tail by a separate quadrature.

Value

A numeric vector: the (log) density for dsnorm(), the probabilities for psnorm() and the quantiles for qsnorm(). dsnorm() has no defaults for xi, omega and alpha. psnorm() and qsnorm() recycle their arguments to the longest, give a zero-length result when an argument has length zero, and keep the names and dimensions of q or p, as stats::pnorm() and stats::qnorm() do. psnorm() returns 0 and 1 at -Inf and Inf, and NA for a missing q, a non-finite alpha or a non-positive or missing scale. qsnorm() returns -Inf and Inf at p of 0 and 1, and NA for p outside [0, 1], a non-finite alpha or a non-positive or missing scale.

References

https://en.wikipedia.org/wiki/Skew_normal_distribution

Examples

x <- seq(-2, 5, length.out = 100)
y <- dsnorm(x, xi = 0, omega = 1, alpha = 5)
plot(x, y, type = "l", main = "Skew Normal Density")

# The quantile function inverts the distribution function
p <- c(1e-10, 0.025, 0.5, 0.975)
q <- qsnorm(p, xi = 1, omega = 2, alpha = -3)
psnorm(q, xi = 1, omega = 2, alpha = -3)

Fit a skew normal distribution to log-density evaluations

Description

Fit a skew normal distribution to log-density evaluations

Usage

fit_skew_normal(x, y, threshold_log_drop = -6, temp = 1)

Arguments

x

A numeric vector of points where the density is evaluated.

y

A numeric vector of log-density evaluations at x, normalised so that max(y) = 0. The function does not normalise y, and the threshold is measured from 0.

threshold_log_drop

A single finite negative number (default -6). Points with y below it are left out of the fit.

temp

A single finite positive number, the temperature of the weights (default 1). NA is not allowed: the temperature is no longer estimated.

Details

The fit is by weighted least squares on the log scale: it minimises \sum_i w_i \{y_i - \log f(x_i)\}^2 over the location, scale and shape of a skew-normal density f and a log-constant logC. The weights w_i \propto \exp(\tau y_i), with \tau = temp, put the fit where the mass is. Points with y below threshold_log_drop are left out of the fit, but the five highest points are always kept.

The fit runs from two starts and keeps the better fit. With \delta = \alpha / \sqrt{1 + \alpha^2}, when the skewness of the scan (from trapezoidal moments of exp(y)) gives |\delta| \ge 0.2, the starts are the moment-based values and their mirror image, with the opposite skew. When the scan is near symmetric, the starts are \delta = \pm 0.5 (alpha of about \pm 0.577), with the mean and standard deviation of the scan. A single start with the wrong sign of skew can stall at alpha = 0 when the skew is mild.

This is the approach of R-INLA, whose C code fit-sn.c it translates, with the temperature fixed rather than estimated.

Value

A list with the fitted parameters:

Examples

# Fit a SN curve to gamma log-density
logdens <- function(x) dgamma(x, shape = 3, rate = 1, log = TRUE)

x_grid <- seq(0.1, 8, length.out = 21)
y_log  <- sapply(x_grid, logdens)
y_log  <- y_log - max(y_log)  # normalise to have maximum at zero

res <- fit_skew_normal(x_grid, y_log, temp = 10)
unlist(res)

# Compare truth vs skew-normal approximation
x_fine <- seq(0.1, 8, length.out = 200)
y_true <- exp(logdens(x_fine))
y_sn   <- dsnorm(x_fine, xi = res$xi, omega = res$omega, alpha = res$alpha)

plot(x_fine, y_true, type = "n", xlab = "x", ylab = "Density", bty = "n")
polygon(c(x_fine, rev(x_fine)), c(y_true, rep(0, length(x_fine))),
        col = adjustcolor("#131516", 0.25), border = NA)
lines(x_fine, y_sn, col = "#00A6AA", lwd = 2)
legend("topright", legend = c("Truth", "SN Approx."),
       fill = c(adjustcolor("#131516", 0.25), NA), border = NA,
       col = c(NA, "#00A6AA"), lwd = c(NA, 2), lty = c(NA, 1),
       bty = "n")

Fit a skew normal distribution to a sample

Description

Fit a skew normal distribution to a sample

Usage

fit_skew_normal_samp(x)

Arguments

x

A numeric vector of sample data.

Details

Uses maximum likelihood estimation to fit a skew normal distribution to the provided numeric vector x. The fit is computed on standardised draws, so it does not depend on the scale of x. The optimiser, stats::nlminb(), uses the analytic gradient and Hessian of the log-likelihood.

The fit runs from up to three starts and keeps the one with the largest likelihood. The first two starts are as in fit_skew_normal(). With \delta = \alpha / \sqrt{1 + \alpha^2}, they are the moment-based values from the sample skewness of x and their mirror image, with the opposite skew. When the moment-based values give |\delta| < 0.2, that is, when the sample skewness of x is below about 0.0018 in absolute value, these two starts are \delta = \pm 0.5. This is rare: for 1000 draws from a normal distribution, it happens in about 1 sample of 50, and in about 1 sample of 17 for 10000 draws.

The third start is the normal distribution with the median and the SD of x, so alpha = 0. The likelihood has a stationary point at alpha = 0 (the normal fit), so a fit from this start alone can stall there when the skew is mild. The third start runs only when the first two fits end on the same side of alpha = 0, or when one of them is not finite. When they end on opposite sides, each side has been searched from a start on that side. This rests on an empirical assumption, not a proof: that the likelihood has at most one optimum on each side of alpha = 0. It held on every set of posterior draws checked. For small bimodal samples (100 draws), the likelihood can have a second, better optimum on the same side, with a larger |\alpha|. No start finds it, so the fit misses it, as did the fits of earlier versions.

When the draws have no finite maximum likelihood estimate, for example a small sample of heavy-tailed draws, the likelihood rises along a ridge towards |\alpha| = \infty. The fit then stops somewhere on the ridge, at |\alpha| of about 10^6. This point depends on the optimiser, so it can differ from that of earlier versions.

Value

A list with the fitted parameters xi (location), omega (scale) and alpha (shape).

Examples

x <- rnorm(100, mean = 5, sd = 1)
unlist(fit_skew_normal_samp(x))

Fit Measures for a Latent Variable Model estimated using INLA

Description

Fit Measures for a Latent Variable Model estimated using INLA

Usage

## S4 method for signature 'INLAvaan'
fitMeasures(object, fit_measures = "all",
  baseline_model = NULL, h1_model = NULL, fm_args,
  output = "vector", level = NULL, ...)

## S4 method for signature 'INLAvaan'
fitmeasures(object, fit_measures = "all",
  baseline_model = NULL, h1_model = NULL, fm_args,
  output = "vector", level = NULL, ...)

Arguments

object

An object of class INLAvaan.

fit_measures

If "all", all fit measures available will be returned. If only a single or a few fit measures are specified by name, only those are computed and returned. The LOO measures "elpd_loo", "se_loo", "p_loo" and "looic" (see loo()), and the WAIC measures "elpd_waic", "se_waic", "p_waic" and "waic" (see waic()), are included in "all" only when stored with the fit (test including "loo", "waic" or "full" in inlavaan(), or add_loo()); otherwise they are computed on demand when requested by name, and recomputed on every call – store the result with fit <- add_loo(fit) (or call loo()/waic() directly) for repeated access. For a fit with sampling weights, which loo() refuses, a LOO or WAIC measure asked for by name is left out with a warning. If no other measure is asked for, the call stops with the error of loo(). INLAvaan's stable spelling fit.measures is also accepted.

baseline_model

The baseline (null) model for the incremental fit indices (BCFI, BTLI, BNFI). NULL (default) fits the independence model automatically, as lavaan does. Supply an INLAvaan object to use another baseline, or FALSE to skip the incremental indices. INLAvaan's stable spelling baseline.model is also accepted; see bfit_indices().

h1_model

Ignored (included for compatibility with the lavaan generic).

fm_args

Ignored (included for compatibility with the lavaan generic).

output

Ignored (included for compatibility with the lavaan generic).

level

Ignored (included for compatibility with the lavaan generic).

...

Additional arguments. Currently supports:

rescale

Character string controlling how the Bayesian chi-square is computed, following blavaan::blavFitIndices(). Options are "devM" (default) which uses the deviance rescaled by pD from DIC, or "MCMC" which uses the classical chi-square ((N-1) * F_ML) and classical degrees of freedom (p - npar) at each posterior sample.

Value

A named numeric vector of fit measures.

See Also

bfit_indices(), compare(), diagnostics()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            silent = TRUE)

# All available fit measures
fitMeasures(fit)

# Specific measures
fitMeasures(fit, c("npar", "dic", "p_dic", "ppp"))



Model-Implied Moments for INLAvaan Models

Description

Extract the model-implied (fitted) sample statistics from a fitted INLAvaan model. As in lavaan and blavaan, the moments are the model-implied covariance matrix (and mean vector, when a mean structure is present) evaluated at the parameter estimates – here the posterior means.

Usage

## S4 method for signature 'INLAvaan'
fitted(object, type = "moments", labels = TRUE, ..., per_cluster = FALSE)

## S4 method for signature 'INLAvaan'
fitted.values(
  object,
  type = "moments",
  labels = TRUE,
  ...,
  per_cluster = FALSE
)

Arguments

object

An object of class INLAvaan.

type

Character. "moments" (default) returns the model-implied variance-covariance matrix and, when relevant, the mean vector. "casewise" (aliases "obs", "ov") returns the model-predicted values for each observation.

labels

Logical. Attach variable names to the output. Default TRUE.

...

Currently unused.

per_cluster

Logical. For a random-slope model, return the moments of each cluster instead of their average. Default FALSE.

Details

This delegates to lavaan's own fitted() machinery, so the return structure matches lavaan exactly. Because INLAvaan stores the posterior means as the point estimates of the fitted object, the implied moments are the posterior-mean model-implied moments (mirroring blavaan).

For a model with random slopes (lavaan's rv()), the moments are averaged over the covariates and include the mean and the variance of each slope. With per_cluster = TRUE, each cluster gets the expected cluster mean and within-cluster covariance (divisor n_j) of its outcomes and covariates at its own covariate values, and the mean also holds the expected values of any between-only outcomes. This is not available for a slope on a latent or split covariate. type = "casewise" gives the outcomes' means given the covariates (closed-form route only).

Value

For type = "moments", a list (or list of lists, for multiple groups) with elements such as cov and mean. For type = "casewise", a numeric matrix of predicted observed-variable values. With per_cluster = TRUE, a list with one element per cluster, each holding cov and mean.

See Also

predict(), coef(), fitMeasures()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "none", silent = TRUE)

# Model-implied covariance matrix (posterior means)
fitted(fit)

# Casewise model-predicted observed values
head(fitted(fit, type = "ov"))



Extract the Internal INLAvaan Object

Description

Returns the inlavaan_internal list stored inside a fitted INLAvaan object, optionally extracting a single named element.

Usage

get_inlavaan_internal(object, what)

Arguments

object

An object of class INLAvaan.

what

Character. Name of the element to extract from the internal list. If missing, the entire list is returned. Common elements include "coefficients", "summary", "Omega", "vcov_x", "theta_star", "approx_data", "pdf_data", "partable", "marginal_method", "nsamp", "mloglik", "DIC", "ppp", "loo", "waic", "test", "vb", "opt", "timing", "visual_debug", "summary_draws", "centred". "centred" holds the names of the intercepts that the fit centres (see centring in inlavaan_control()), and is empty when it centres none.

Value

The full inlavaan_internal list, or the named element when what is supplied.

The marginals in approx_data

approx_data is a matrix with a row for each skew-normal marginal of the fit. Its columns xi, omega and alpha are the location, the scale and the shape that dsnorm(), psnorm() and qsnorm() take, so the density, the distribution function and the quantiles of every parameter follow from it. The other columns describe how each marginal was fitted (see diagnostics()).

The draws in summary_draws

summary_draws holds the posterior draws of the rows that the fit summarises from draws without a fitted skew-normal: the covariances, the centred intercepts, the ⁠:=⁠ parameters and the composite variances and intercepts when marginal_method = "gaussian" or sn_fit_sample = FALSE. It is a matrix with one row per draw and one column per parameter, named as the rows of summary. parameterestimates() takes their quantiles for the interval at any level. The centred intercepts have a draw of their own, of 20000 draws or nsamp when that is larger (see centring in inlavaan_control()). The matrix then has as many rows as the larger draw, and a column of the other draws is NA below its nsamp draws.

See Also

INLAvaan, diagnostics(), timing()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "none", silent = TRUE)

# Full internal object
int <- get_inlavaan_internal(fit)
names(int)

# Extract a specific element
get_inlavaan_internal(fit, "coefficients")

# The 97.5% point of the first free parameter, from its skew-normal row
sn <- get_inlavaan_internal(fit, "approx_data")[1, ]
pt <- get_inlavaan_internal(fit, "partable")
ginv <- pt$ginv[[which(pt$free == 1)[1]]]
ginv(qsnorm(0.975, sn[["xi"]], sn[["omega"]], sn[["alpha"]]))



Fit an Approximate Bayesian Latent Variable Model

Description

This function fits a Bayesian latent variable model by approximating the posterior distributions of the model parameters: it finds the posterior mode, takes the Laplace approximation there, corrects its mean by variational Bayes, and fits a skew-normal or a Gaussian marginal to each parameter. It leverages the lavaan package for model specification and estimation.

Usage

inlavaan(
  model,
  data = NULL,
  model.type = "sem",
  dp = priors_for(),
  test = "standard",
  vb_correction = c("onestep", "full", "none"),
  marginal_method = c("skewnorm", "gaussian"),
  marginal_scan = c("linear", "exact", "laplace", "plain"),
  marginal_laplace_fallback = FALSE,
  nsamp = 1000,
  cov_as_cor = FALSE,
  sn_fit_sample = TRUE,
  control = list(),
  verbose = FALSE,
  silent = FALSE,
  start = NULL,
  cores = NULL,
  ppp_method = c("onestep", "em"),
  ppp_nsamp = 250L,
  wiggle = NULL,
  wiggle.sd = 0.1,
  n_qmc = NULL,
  vb_method = NULL,
  marginal_correction = NULL,
  samp_copula = NULL,
  samp_norta = NULL,
  sn_fit_ngrid = NULL,
  sn_fit_logthresh = NULL,
  sn_fit_temp = NULL,
  debug = NULL,
  add_priors = NULL,
  optim_method = NULL,
  numerical_grad = NULL,
  hessian_method = NULL,
  ...
)

Arguments

model

A description of the user-specified model. Typically, the model is described using the lavaan model syntax. See model.syntax for more information. Alternatively, a parameter table (e.g., the output of the lavParTable() function) is also accepted.

data

An optional data frame containing the observed variables used in the model. The variables must be continuous: an ordered factor in the model stops the fit, as this version does not fit ordinal or binary indicators (see the section "Ordinal and binary data" of inlavaan()).

model.type

The lavaan entry point used to fit model: "cfa", "sem", or "growth" (matching lavaan's model-specific wrapper functions), or "lavaan" for the general-purpose interface. Other values give an error. Set automatically by acfa(), asem(), and agrowth(); documented explicitly here because lavaan >= 0.7-1 renamed the corresponding simulateData() argument to model_type, so it can no longer be inherited from there.

dp

Default prior distributions for the different types of model parameters; a named character vector as returned by priors_for(). Types left out take their default priors. A name that is not a type, such as a misspelt one, gives a warning. dp = blavaan::dpriors() works too.

test

Character vector naming the post-estimation quantities to compute and store with the fit. The atoms are "ppp" (posterior predictive p-value), "dic" (deviance information criterion and its pD), "loo" (leave-one-out cross-validation, see loo()) and "waic" (see waic()). Three aliases stand for sets of atoms: "standard" (the default) and its synonym "default" give c("ppp", "dic"); "full" gives all four; "none" gives nothing. Aliases and atoms may be mixed and are unioned, so test = c("standard", "loo") adds the LOO to the default set. The LOO and the WAIC come from one Taylor pass, so asking for either stores both. They run only when asked for, with no time budget. On a model the casewise machinery does not support (a fit with sampling weights) they are skipped with a warning and the rest of the fit proceeds. For a two-level model the PPP follows blavaan: each of ppp_nsamp posterior draws generates replicate data, which are scored against the saturated model (see ppp_method). The two-level PPP is experimental. The fit records what was requested and what was computed (get_inlavaan_internal(fit, "test")); summary(), fitmeasures(), deviance(), logLik() and timing() report only what was computed. add_loo() stores the LOO and WAIC post hoc; loo() and waic() compute on demand. For a random-slope model "ppp" is dropped, with a warning when it was asked for and a message otherwise (see the Random slopes section of inlavaan()). "dic", "loo" and "waic" are unaffected.

vb_correction

The variational Bayes (VB) correction of the posterior mean of the Laplace approximation. "onestep" (default) takes one step from the mode and checks it. Where the check fails, the posterior is far from Gaussian along the step: the fit then solves the VB equation instead, and warns (see diagnostics()). "full" iterates the correction to its fixed point, and "none" leaves it out. The correction moves the marginal log-likelihood, the point at which the DIC is computed, the centre of the LOO and the WAIC, and the Gaussian marginals of marginal_method = "gaussian" and their draws. It does not move the skew-normal marginals or their draws, which are scanned from the mode. The intercepts of a saturated mean structure are the exception: a single-level model of one group with complete data and meanstructure = TRUE, in which every observed variable has a free intercept of its own with a normal prior, and which has no free latent mean, no observed variable in a regression, no equality constraint and no composite. They are not scanned (their nmad in diagnostics() is NA, which is the way to tell): with either marginal_method their marginals are Gaussian and centred at the VB mean. So the correction also moves these marginals, their draws and what is computed from them.

marginal_method

How the marginal posterior of each parameter is approximated. "skewnorm" (default) fits a skew-normal distribution to a scan of the log-posterior along the parameter (see marginal_scan). "gaussian" takes the Gaussian marginal of the Laplace approximation, centred at the VB mean, which is faster. [Deprecated] The old values warn: "marggaus" is the old name of "gaussian", and "asymgaus" now runs "skewnorm". "sampling" is kept for a sampler that is under development, and gives an error.

marginal_scan

How the scan behind each skew-normal marginal is taken. "linear" (default) scans along a straight line through the mode, and adds a linear correction for the changing volume of the other parameters. "exact" computes that volume term exactly at each point of the scan. "laplace" maximises the log-posterior over the other parameters at each point of the scan, and takes the height and the volume there. "plain" adds no volume correction. On the Holzinger and Swineford and the Political Democracy models, "exact" and "laplace" take 10 to 25 times as long as "linear". Ignored with marginal_method = "gaussian", which has no scan.

marginal_laplace_fallback

Logical. Rescan with marginal_scan = "laplace" only the parameters whose ridge bend is above 0.25 (see diagnostics())? Default FALSE, so that a fit costs what marginal_scan says. With TRUE, the parameters where the default scan is likely to give too small a posterior SD get the slower scan, and the others keep the fast one. The column ridge_bend of diagnostics(fit, "param") shows which parameters these are. Ignored with marginal_method = "gaussian" and with marginal_scan = "laplace".

nsamp

The number of samples to draw for all sampling-based approaches (including posterior sampling for model fit indices). A fit that summarises some parameters from the draws needs at least 2: the free covariances and the ⁠:=⁠ and ⁠~*~⁠ parameters. The intercepts that the fit centres have a draw of their own (see centring in inlavaan_control()).

cov_as_cor

Logical. Residual and latent-disturbance covariance parameters (⁠~~⁠ between two observed or two latent variables) are always estimated on the correlation scale internally (an atanh link, the same as for std.ov/std.lv-standardised parameters); by default their reported marginal is then re-derived on the covariance scale \sigma_i \sigma_j \rho from a posterior sample (see nsamp), because that is the scale lavaan/blavaan report by default. When TRUE, that re-derivation is skipped and each such parameter's own directly profiled correlation-scale marginal \rho \in (-1, 1) is reported instead – useful for comparing the profiling machinery (skew-normal fit, VB, ...) against a correlation-scale reference without the sampling/copula step in between. Model estimation is identical either way; only what is reported for these parameters changes. The returned parameter table keeps their covariance classes, so loo() and waic() after the fit score the same model, and the setting is stored as get_inlavaan_internal(fit)$cov_as_cor. The point estimates of these parameters are correlations, so methods that use the point estimates as model parameters (such as fitted() and residuals()) are not meaningful when TRUE. Not the same as lavaan's std.ov/std.lv, which re-parameterises the whole model on a standardised scale. Defaults to FALSE.

sn_fit_sample

Logical. When TRUE (default), a parametric skew-normal is fitted to the posterior samples for covariance and defined parameters. When FALSE, these are summarised using kernel density estimation instead.

control

A list of tuning settings, made by inlavaan_control(), or a plain list with some of its names: the limits of the search for the posterior mode, of the VB correction and of the skew-normal scans, and the settings hessian, debug, add_priors and centring. The defaults suit most fits. An unknown name gives an error. The controls of stats::nlminb() that control took up to INLAvaan 0.3.5, such as iter.max, still work, with a deprecation warning. See inlavaan_control().

verbose

Logical. With FALSE (default) the fit prints one line per stage. With TRUE it also prints the details of each stage of the fit on the internal scale: the start, the mode search, the VB correction and the marginals, with their checks. Use silent = TRUE to print nothing.

silent

Logical. Print nothing at all, and muffle the warnings and messages raised during the fit? Default FALSE. verbose and silent cannot both be TRUE. Errors are still raised. Whether or not silent is TRUE, the texts of the warnings raised during the fit are recorded in the field warnings of get_inlavaan_internal().

start

Optional numeric vector of starting values for the optimiser, given as a full vector of free parameters in the internal (unconstrained) parameterisation. Mainly for internal use by update(), which warm-starts mode-finding from a previous fit's posterior mode when the free parameters keep their names; supplying a hand-built vector requires knowledge of the internal parameter ordering. Its length must equal the number of free parameters or an error is raised. An intercept that the fit centres (see centring in inlavaan_control()) takes its start in its centred coordinate.

cores

A positive whole number or NULL. The number of cores. Other values, such as 0, 2.5 or NA, give an error. With NULL (default), the scans of the skew-normal marginals follow future::plan(), which is serial unless a plan is set, and the LOO and the WAIC asked for in test run serially. With cores > 1, the scans run in parallel when the packages future and parallelly are installed, and serially otherwise. The LOO and the WAIC are then forked via parallel::mclapply() where that is safe, or run over a PSOCK cluster (separate R processes) inside IDE R sessions (RStudio, Positron) and on Windows. 1 is serial.

ppp_method

How the PPP of a two-level model scores the observed and the replicate data against the saturated model. "onestep" (default) takes one Fisher-scoring step from the moments of each posterior draw towards the saturated fit, and fits by EM where the step would leave the valid covariance matrices (with few clusters or a small between variance). With missing = "ml", "onestep" instead finds the saturated fit of each replicate by quasi-Newton steps from the moments of the posterior draw, which reach the maximum that the EM finds, and fits by EM where they do not converge. "em" always fits the saturated model by EM, as blavaan does. Ignored for single-level models.

ppp_nsamp

The number of posterior draws, each with one replicate data set, that the PPP of a two-level model uses. Defaults to 250, and is capped at nsamp. Draws that cannot be scored are left out, with a warning. Ignored for single-level models.

wiggle

Equality constraints to relax into approximate ones, as in blavaan. NULL (the default) keeps every equality exact. A character vector. Each entry is a label that the model gives to two or more free parameters (such as a in c(a, a)*x2), or one of the types "loadings", "intercepts" (of observed variables), "means" (of latent variables) and "regressions". A type takes every set of parameters of that type that group.equal or a shared label holds equal. A label that is also a type name is read as the label. In each set, the first parameter in the parameter table (with group.equal, the one of the first group) keeps its prior. Each other parameter becomes a free parameter of its own, with a normal prior centred on the first parameter and with standard deviation wiggle.sd, in place of the equality and of its own prior. Parameters that wiggle does not select stay exactly equal. Variances, covariances, thresholds, a label on parameters of two types (such as a loading and an intercept) and models with composites are not supported. See the section "Approximate equality constraints" of inlavaan().

wiggle.sd

The standard deviation of the normal priors that wiggle sets, on the scale of the parameters. One positive number for all entries of wiggle, or one for each entry, in the same order. The default is 0.1, as in blavaan, and NULL also gives it. wiggle_sd is the same argument. A small value keeps the parameters of a set close together, and a large value lets them differ.

n_qmc

[Deprecated] Has no effect. The VB correction now takes a deterministic step, with no quasi-Monte Carlo nodes.

vb_method

[Deprecated] Has no effect. The VB correction now has one rule, and vb_correction = "full" iterates it.

marginal_correction

[Deprecated] Use marginal_scan. "none" and FALSE are marginal_scan = "plain", which gives the same fit. "shortcut", "shortcut_fd" and "hessian" run marginal_scan = "linear".

samp_copula

[Deprecated] Has no effect. The draws always couple the fitted marginals by a Gaussian copula. With marginal_method = "gaussian" they are the draws of the Laplace approximation.

samp_norta

[Deprecated] Has no effect. The draws no longer adjust the correlations of the copula.

sn_fit_ngrid

[Deprecated] Use control = inlavaan_control(n_grid = ), which gives the same fit.

sn_fit_logthresh

[Deprecated] Use control = inlavaan_control(log_threshold = ), which gives the same fit.

sn_fit_temp

[Deprecated] Has no effect. The skew-normal marginals are fitted with temperature 1.

debug

[Deprecated] Use control = inlavaan_control(debug = TRUE), which gives the same fit.

add_priors

[Deprecated] Use control = inlavaan_control(add_priors = FALSE), which gives the same fit.

optim_method

[Deprecated] Has no effect. The posterior mode is always found by stats::nlminb().

numerical_grad

[Deprecated] Has no effect. The fit always uses the analytic gradient.

hessian_method

[Deprecated] Use control = inlavaan_control(hessian = ), which gives the same fit.

...

Additional arguments to be passed to the lavaan model fitting function.

Value

An S4 object of class INLAvaan which is a subclass of the lavaan class.

Deprecated arguments

The arguments marked deprecated still work in INLAvaan 0.4.0, and stop from 0.5.0. Each warns once per session, with a warning of class inlavaan_deprecated that names what to use instead. With options(inlavaan.deprecation = "error") they stop now, so that tests can find old calls. Those that moved into control give the same fit. The others have no effect. INLAvaan 0.3.5 has the old methods.

Ordinal and binary data

This version of INLAvaan fits continuous data only. A model with an ordinal or binary variable stops with an error of class inlavaan_ordinal, which names the variables. That is the case for an ordered factor in data that the model uses (as an indicator or as a covariate), the lavaan argument ordered, thresholds (|) in the model or in a parameter table, and sample thresholds (sample.th). An estimator that lavaan uses for ordinal data, such as "WLSMV" or "PML", stops the fit too. When it is the only sign of ordinal data, its error also has the class inlavaan_estimator, the class of the error for any other estimator than "ML" (or lavaan's "default"). A variable coded as numbers, such as 0 and 1, is read as continuous, as lavaan reads it. To use an ordered covariate by its codes, convert it with as.numeric() before the fit.

Earlier versions fitted ordinal data by a pairwise likelihood, whose fit indices and marginal likelihood do not have their usual meaning. For a fit of ordinal data saved by such a version, parameterestimates(), summary(), predict() with newdata, loo(), waic() and bfit_indices() stop with an error of class inlavaan_ordinal. Ordinal and binary data return in a later release, with a new method. Until then, fit such models with lavaan (for example with estimator = "WLSMV") or blavaan.

Approximate equality constraints

wiggle turns sets of parameters that are held equal into sets of parameters that are held close. In a set of K parameters x_1, \dots, x_K, the first one in the parameter table keeps its own prior p_0, and each other one gets a normal prior centred on it:

x_1 \sim p_0, \qquad x_k \mid x_1 \sim N(x_1, \sigma_w^2), \quad k = 2, \dots, K,

where \sigma_w is wiggle.sd. With three groups or more, every other parameter is centred on the one of the first group, not on that of the group before. These priors replace the equality and the own priors of x_2, \dots, x_K, and their normalising constants are kept, so the marginal log-likelihood of compare() is that of this model. This is the posterior that blavaan 0.6-1 means to sample with target = "stan", and in the usual call with group.equal, acfa(..., wiggle = ) and blavaan::bcfa(..., wiggle = ) fit the same model. In two cases blavaan 0.6-1 gives some of these parameters another prior, and so samples another posterior: when the model also sets priors with prior(), and when the rows of a set come in the model syntax in another order than in blavaan's model matrices (for example speed ~ a*textual written before textual ~ a*visual). INLAvaan always gives each relaxed parameter the prior above, whatever the order of the rows.

Each relaxed parameter counts as a free parameter: in npar of fitmeasures() and in the number of model parameters in the header of summary(). blavaan 0.6-1 counts the parameters of the exact equalities instead, so the fit indices of fitmeasures() with rescale = "MCMC", which use npar, differ from those of blavaan. The default rescale = "devM" uses the effective number of parameters, pD.

A relaxed parameter keeps its row of the parameter table but loses the shared label, so it is named by its row, for example ⁠x1~1.g2⁠ in coef(), and the label (such as .p16. or a) names the first parameter only. A definition with ⁠:=⁠ that uses the label uses the first parameter. The prior of a relaxed parameter shows in summary() as ⁠normal(<first parameter>,<wiggle.sd>)⁠, for example normal(.p16.,0.05), and the header gives the number of approximate equalities. As in lavaan, summary() shortens long labels in its label column, so .p16. shows there as ⁠.16.⁠. The columns wiggle_anchor (the row of the first parameter) and wiggle_sd of lavaan::parTable() hold the same information.

A set can span the groups of a multigroup model and the levels of a two-level model. The parameters on the identity scale can be relaxed: loadings, regressions, intercepts and latent means. Thresholds are not supported: blavaan relaxes them on the scale of the gaps between thresholds, and INLAvaan puts their prior on the thresholds, so the same wiggle.sd would give another model. Each set holds parameters of one type: a label on a loading and an intercept, say, stops with an error, as blavaan refuses an equality across its model matrices. An entry of wiggle that selects no parameters held equal stops with an error. blavaan 0.6-1 ignores some such entries without a word.

A small wiggle.sd gives nearly the fit with the exact equalities, and a large one nearly the fit without them. Far below the posterior standard deviations, wiggle.sd makes the posterior very narrow along the differences, and the fit can warn of a near-singular Hessian: use the exact equality then. With group.equal = "intercepts", the latent means of the later groups are free, and only the equal intercepts identify them. A large wiggle.sd on the intercepts then leaves these latent means weakly identified, and their posteriors wide, as in blavaan.

Random slopes

Wrapping a level-1 regression coefficient in lavaan's rv() modifier turns it into a level-2 latent variable – a random slope – which can then be given a mean, a variance and cross-level regressions like any other level-2 latent variable:

level: 1
  fw =~ y1 + y2 + y3
  fw ~ rv('s1')*x1
level: 2
  fb =~ y1 + y2 + y3
  s1 ~ w1
  s1 ~~ s1
  s1 ~ 1

The slope's variance and intercept are added automatically, so in practice only the cross-level regression s1 ~ w1 need be written out. summary() marks the level-1 carrier row as x1 (s1): that row is fixed at zero, the slope itself being reported under Level 2.

The likelihood takes one of two routes. When the covariate carrying the slope is observed and purely within-cluster, the slope integrates out in closed form. When it is latent, or split across both levels (the same variable entering at level 1 and at level 2), the integral is done by Gauss-Hermite quadrature instead; that route warns at fit time and is governed by integration.ngh, passed through to lavaan. The node count is an accuracy setting as much as a cost setting, so give every fit that is to be compared with another the same integration.ngh.

With fixed.x = TRUE (the default) the likelihood is the density of the outcomes given the observed exogenous covariates. With fixed.x = FALSE the covariates are modelled too: their two-level normal density, with their means, variances and covariances as parameters, is added to the likelihood, which lavaan itself does not do. The other parameters then have the same posterior as under fixed.x = TRUE. This needs a slope on an observed within-cluster covariate, every covariate without a slope observed at one level only, and complete covariates; other fixed.x = FALSE fits are refused. A model whose covariates are all latent has nothing to hold fixed, and lavaan reports fixed.x = FALSE for it of its own accord; such a fit is accepted as it stands.

Equality constraints work as for other models, except that covariances cannot be held equal. Composites (⁠<~⁠) cannot be combined with random slopes yet.

A random-slope model implies no single within-cluster covariance matrix: the covariance of the outcomes depends on the covariate values. fitted() and residuals() therefore use the implied moments averaged over the covariates, which include the mean and the variance of each slope, or with per_cluster = TRUE the moments of each cluster at its own covariate values (closed-form route only). standardisedsolution() and the standardised columns and R-square of summary() are scaled by the averaged variances. The carrier row x1 (s1) then gives the standardised mean slope, and the slope's own rows are on the same standardised scale. An outcome observed at level 1 only, whose slope covariate has a non-zero mean, has no place in lavaan's two-level layout, and these outputs abort for it.

simulate() draws each cluster's slopes and other level-2 effects and then its outcomes, at the cluster's own covariates (closed-form route only). sampling() gives latent, observed and implied draws. predict() gives type = "lv" and, on the closed-form route, the cluster-specific "yhat" and "ypred" from the empirical Bayes random effects, while fitted(type = "casewise") gives the outcomes' means given the covariates. bfit_indices() scales the Bayesian fit indices against the unrestricted random-coefficient model with the same random-effects design, because a saturated model does not exist here. This reference is INLAvaan's own construction (closed-form route only).

The posterior predictive p-value (test = "ppp") is dropped, because a random-slope model has no saturated model to score replicate data against. What aborts with an explanation: the residual types scaled by standard errors, predict(type = "ymis"), and loo(type = "loso"), which would need a cluster's sufficient statistics downdated by one row.

The model-comparison side works throughout. compare() reports the marginal likelihood, Bayes factors, the DIC and its p_D, and loo() and waic() score the fit leave-one-cluster-out on the conditional likelihood.

To ask whether there is a random slope at all, compare the fit with the fixed-slope model (fw ~ x1 at level 1) using compare(). On the closed-form route, fixing the slope variance at zero (s1 ~~ 0*s1) and dropping any cross-level regression on the slope gives the same model. Keeping s1 ~ w1 gives a cross-level interaction model instead. The quadrature route refuses a slope variance fixed at zero.

See Also

Typically, users will interact with the specific latent variable model functions instead, including acfa(), asem(), and agrowth().

Examples

# The Holzinger and Swineford (1939) example
HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")

fit <- inlavaan(
  HS.model,
  data = HolzingerSwineford1939,
  auto.var = TRUE,
  auto.fix.first = TRUE,
  auto.cov.lv.x = TRUE
)
summary(fit)

Tuning of an INLAvaan fit

Description

Builds the control list of inlavaan(), acfa(), asem() and agrowth(): the limits of the search for the posterior mode, of the VB correction and of the skew-normal scans, and four settings for checks and development. The defaults suit most fits, so most users never need it. A plain list with some of these names works too, and is checked by the same rules: control = list(n_grid = 31) is the same as control = inlavaan_control(n_grid = 31).

Usage

inlavaan_control(
  mode_maxit = 5000L,
  mode_maxeval = 5000L,
  mode_tol = 1e-10,
  vb_maxit = 25L,
  vb_tol = 0.001,
  vb_budget = 2,
  n_grid = 21L,
  log_threshold = -6,
  nlminb = list(),
  hessian = c("central", "forward"),
  debug = FALSE,
  add_priors = TRUE,
  centring = TRUE
)

Arguments

mode_maxit, mode_maxeval

The largest number of iterations, and of evaluations of the log-posterior, of the search for the posterior mode by stats::nlminb() (its iter.max and eval.max). When the search stops short of the mode, it starts once more from where it stopped, with each parameter scaled by its curvature and the same limits.

mode_tol

The relative tolerance of the search for the posterior mode (the rel.tol of stats::nlminb()).

vb_maxit, vb_tol

The largest number of iterations, and the tolerance in posterior SDs, of the fixed-point iteration of the VB correction. They act with vb_correction = "full", and on the solve that follows a failed check of the default one-step correction. A first step below vb_tol in every parameter is not checked.

vb_budget

The cap on the solve that follows a failed check of the default one-step correction. The solve and the two passes of the check together take at most vb_budget times the evaluations of the log-posterior, of its gradient and of the Hessian that the search for the posterior mode and the Hessian made, in passes of the rule of 2m + 1 gradients each, for m parameters. Default 2. 1 is the cap of earlier development versions, Inf lifts the cap, so that the solve stops only at vb_tol or after vb_maxit iterations, and 0 leaves a flagged fit at its mode. A single number of at least 0. A fit that passes the check does not depend on it. The cap scales with the cost of the search for the mode, so a search from a good start, as in a warm-started update(), leaves less room for the solve. For a model with a saturated mean structure (see vb_correction in inlavaan()), or with hessian = "forward", INLAvaan gives the engine the Hessian at the mode, and the cap counts it as the evaluations of the central differences that it replaces. So the cap, and a solve that reaches it, almost always do not depend on how that Hessian was taken.

n_grid

The number of points of the scan of each skew-normal marginal, over 4 posterior SDs on each side of the mode. At least 7. It replaces the deprecated argument sn_fit_ngrid of inlavaan().

log_threshold

Points of the scan whose log-posterior falls more than this below the maximum are left out of the skew-normal fit. The five highest points are always kept. A single negative number. It replaces the deprecated argument sn_fit_logthresh of inlavaan().

nlminb

A named list of other controls of stats::nlminb() for the search for the posterior mode, such as trace = 1, which prints its iterations, or abs.tol. Its iter.max, eval.max and rel.tol stand in for mode_maxit, mode_maxeval and mode_tol, which must then not be set too. It does not reach the optimiser that the VB correction falls back to.

hessian

How the Hessian at the posterior mode is differenced from the analytic gradient. "central" (default) costs two gradient evaluations per parameter. "forward" costs about half as much but is less accurate, and suits models with many parameters and large samples. It replaces the deprecated argument hessian_method of inlavaan().

debug

Logical. With TRUE, the fit returns its internal list (see get_inlavaan_internal()) instead of an INLAvaan object, for development. Default FALSE. It replaces the deprecated argument debug of inlavaan().

add_priors

Logical. With FALSE, the log-posterior leaves out the priors, so that the posterior mode is the maximum likelihood estimate. Only the mode is meaningful then. Default TRUE. It replaces the deprecated argument add_priors of inlavaan().

centring

Logical. With TRUE (default), the approximation holds some free intercepts in other coordinates, and the model stays the same. An intercept moves when a mean that is not zero reaches its variable through the coefficients of the model: the mean of an exogenous observed covariate (with fixed.x = TRUE or FALSE, or conditional.x = TRUE), the intercept of an observed variable that predicts other variables, or the mean or intercept of a latent variable. A fixed mean, such as that of a covariate under fixed.x = TRUE, counts unless it is zero up to rounding (below about 1.5e-8). So a covariate centred over other rows than those that the fit uses still moves the intercepts. The intercept is then held at the implied mean of its variable, or near it: an intercept held equal across groups takes the shift of its first group, and a variable on a feedback loop does not pass its mean on. Without this, such an intercept and the coefficients on the path are almost collinear, and their posterior SDs come out too small. The change of coordinates has Jacobian 1, so the exact posterior, its mode and the marginal likelihood do not change. Their approximations do, so the reported marginal log-likelihood can move a little. The data, the priors and every reported value stay on the raw scale: the summary, parameterestimates(), coef(), sampling(), predict(), loo(), waic() and simulate() use the raw intercepts. The summaries of these intercepts come from posterior draws of their own: 20000 draws from the same approximation, or nsamp when that is larger. This draw computes no likelihood, and it leaves the random numbers of the rest of the fit as they are, so nsamp sets only the other draws, and such a fit needs none of them. Their SDs, quantiles and fitted skew-normal marginals carry the Monte Carlo error of this draw. On the models checked, the error (one SD) of the 2.5% and 97.5% points was at most 0.024 posterior SDs, where 1000 draws gave up to 0.10, and a skew-normal fitted to 1000 nearly normal draws could take a skew that the posterior does not have. Most of the cost of the draw is that of the skew-normal fits to it, and on these models it took from 2% to 19% of the time of the fit. Their means come from a control variate. Their Monte Carlo error is 0 for an indicator whose loading is fixed, and small for the others: in a MIMIC model with a covariate mean near 13, 0.13% of the posterior SD of an intercept. The means implied at the estimates, as in fitted() and residuals(), carry this error too, and there it was about 1.6% of their own, much smaller, posterior SD. The internal values hold the centred value of such an intercept: the start of inlavaan(), the theta of loo(), sampling(type = "theta"), vcov(type = "theta"), the "truth_theta" of simulate(), diagnostics(type = "param"), the column par of lavaan::parTable(), and the first rows of approx_data (see get_inlavaan_internal()). Only single-level ML fits with a mean structure and without composites or thresholds are centred. FALSE keeps every intercept as it is, as in INLAvaan 0.4.0, for comparisons and bug reports.

Details

Give each setting in one place only: an entry and the deprecated argument of inlavaan() that it replaces (for example n_grid and sn_fit_ngrid) cannot both be set, and neither can an entry and its twin in nlminb.

Up to INLAvaan 0.3.5, control was a list of controls of stats::nlminb(), such as control = list(iter.max = 2000). These names still work in control, with a deprecation warning, and stop from INLAvaan 0.5.0: iter.max, eval.max and rel.tol set mode_maxit, mode_maxeval and mode_tol, and the others go to nlminb.

Value

A list of the entries that were set, checked, for the control argument of inlavaan(). An entry left out takes its default. An iter.max, eval.max or rel.tol given in nlminb is returned as mode_maxit, mode_maxeval or mode_tol.

See Also

inlavaan(), stats::nlminb()

Examples

# A finer scan of each skew-normal marginal
inlavaan_control(n_grid = 31)

# Print the iterations of the search for the posterior mode
inlavaan_control(nlminb = list(trace = 1))

# An iter.max in nlminb stands in for mode_maxit
inlavaan_control(nlminb = list(iter.max = 200))

# Keep every intercept in raw coordinates, as in INLAvaan 0.4.0
inlavaan_control(centring = FALSE)


utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(
  "visual =~ x1 + x2 + x3",
  HolzingerSwineford1939,
  test = "none",
  control = inlavaan_control(n_grid = 31)
)

# The same with a plain list
fit <- acfa(
  "visual =~ x1 + x2 + x3",
  HolzingerSwineford1939,
  test = "none",
  control = list(n_grid = 31)
)


Helper function to check if two functions are the same

Description

Helper function to check if two functions are the same

Usage

is_same_function(f, g)

Arguments

f, g

Functions to compare.

Value

Logical.

Examples

f1 <- function(x) { x^2 + 1 }
f2 <- function(x) { x^2 + 1 }
is_same_function(f1, f2)  # TRUE

Log-Likelihood for INLAvaan Models

Description

Extract a log-likelihood-flavoured summary from a fitted INLAvaan model. Two distinct quantities are available, deliberately not conflated: the Bayesian marginal log-likelihood (the default) and the classical log-likelihood evaluated at a point estimate.

Usage

## S4 method for signature 'INLAvaan'
logLik(object, type = c("marginal", "plugin"), ...)

## S4 method for signature 'INLAvaan'
AIC(object, ..., k = 2)

## S4 method for signature 'INLAvaan'
BIC(object, ...)

Arguments

object

An object of class INLAvaan.

type

Character. "marginal" (default) returns the Laplace-approximated marginal log-likelihood (log evidence), the same quantity compare() uses for Bayes factors. "plugin" returns the classical log-likelihood evaluated at the centre of the posterior approximation, the plug-in point of the DIC (see deviance()), with df/nobs attributes and class "logLik" so it supports AIC/BIC at the point estimate. Requires the model to have been fitted with a test that includes "dic" (the default "standard" does).

...

Currently unused.

k

Numeric penalty per parameter passed to the (disabled) AIC() method; see stats::AIC(). Defaults to 2.

Details

The marginal log-likelihood already integrates over the (Laplace- approximated) posterior, so it is not on the same scale as a classical log-likelihood and should not be passed to AIC()/BIC() – doing so would double-penalise model complexity that the evidence has already accounted for. Use compare() to compare models via Bayes factors, DIC, or LOO/WAIC. The plug-in variant exists for users who specifically want a point-estimate-based classical comparison.

AIC()/BIC() on an INLAvaan fit are themselves disabled (mirroring anova()): both are large-sample asymptotic approximations to quantities INLAvaan already computes directly – AIC approximates predictive accuracy, which loo()/waic() already estimate more rigorously; BIC approximates -2 times the log marginal likelihood, which logLik() already returns directly (up to the Laplace approximation). Point-estimate AIC/BIC remain available for reporting-convention purposes via AIC(logLik(object, type = "plugin")) / BIC(logLik(object, type = "plugin")).

Value

For type = "marginal", a length-one numeric of class inlavaan_logLik that prints with a note on its interpretation. For type = "plugin", a standard "logLik" object.

See Also

deviance(), compare(), loo(), waic()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "standard", silent = TRUE)

# Marginal log-likelihood (log evidence)
logLik(fit)

# Classical log-likelihood at the plug-in point, AIC/BIC-compatible
ll <- logLik(fit, type = "plugin")
AIC(ll)



Approximate Leave-One-Out Cross-Validation for INLAvaan Models

Description

Computes leave-one-out (LOO) cross-validation for a fitted INLAvaan model from a single fit, with no refitting and no sampling, via a Taylor approximation of the case-deletion posterior around the Laplace summary. Single-level models are scored per subject (leave-one-subject-out, LOSO); two-level models are scored per cluster (leave-one-cluster-out, LOCO).

Usage

loo(x, ...)

## S3 method for class 'INLAvaan'
loo(
  x,
  type = c("auto", "loso", "loco"),
  units = NULL,
  second_order = TRUE,
  theta = NULL,
  Omega = NULL,
  cores = NULL,
  verbose = FALSE,
  ...
)

## S3 method for class 'inlavaan_internal'
loo(
  x,
  type = c("auto", "loso", "loco"),
  units = NULL,
  second_order = TRUE,
  theta = NULL,
  Omega = NULL,
  cores = NULL,
  verbose = FALSE,
  ...
)

add_loo(object, cores = NULL, verbose = FALSE)

## S3 method for class 'inlavaan_loo'
print(x, ...)

## S3 method for class 'inlavaan_loo'
summary(object, ...)

Arguments

x

A fitted INLAvaan object (or its inlavaan_internal list).

...

Not used, beyond catching the deprecated argument name Sigma (see Omega).

type

Unit type: "auto" (default) resolves to "loso" (per-subject) for single-level models and "loco" (per-cluster, marginal predictive) for two-level models. "loco" cannot be forced on a model without clusters; "loso" on a two-level model scores the conditional (leave-one-unit-out) predictive instead (with a warning; see Details).

units

Optional integer vector of unit indices to score; defaults to all units. For LOSO these are case numbers (row numbers of the analysed dataset); for LOCO, cluster positions. A multigroup two-level fit numbers the clusters (or rows) of group 1 first, then those of group 2, and so on. For a random-slope fit the per-cluster kernels return every cluster on each call, so this trims the reported table rather than the work.

second_order

Logical; compute the second-order correction (default TRUE). FALSE skips the Hessian stage and reports first-order estimates, which cannot be compared across models of different dimension (see Details).

theta, Omega

Optional posterior mean vector and covariance matrix (in the unconstrained parameter space, as stored in theta_star and Omega) at which to evaluate the LOO instead of the fit's own Laplace summary. See Details. They must be in the coordinates of the fit: an intercept that the fit centres is in its centred coordinate (see centring in inlavaan_control()). So do not pass the theta_star of a centred fit to a fit that is not centred, or the other way round.

cores

Number of cores for the Hessian stage. The default NULL runs serially; parallelism must be requested explicitly.

verbose

Logical; print progress (default FALSE).

object

A fitted INLAvaan object, or an inlavaan_loo result for summary().

Details

For a unit u (a subject for LOSO, a cluster for LOCO) with log-likelihood contribution \ell_u(\theta), score s_u and Hessian H_u evaluated at the posterior summary (\theta^*, \Omega), the log conditional predictive ordinate is approximated to first and second order by

\log \mathrm{CPO}_u^{(1)} = \ell_u - \tfrac{1}{2} s_u' \Omega s_u,

\log \mathrm{CPO}_u^{(2)} = \ell_u - \tfrac{1}{2} s_u' (\Omega^{-1} + H_u)^{-1} s_u + \tfrac{1}{2} \log |I + \Omega H_u|.

The reported elpd_loo is the sum of the second-order terms (first-order when second_order = FALSE), with standard error \sqrt{n \, \mathrm{var}(\log \mathrm{CPO}_u)} and looic = -2 \, \mathrm{elpd}. p_loo is the loo package's effective number of parameters, p_{\mathrm{loo}} = \sum_u (\mathrm{lpd}_u - \log \mathrm{CPO}_u), where \mathrm{lpd}_u is the analogous Taylor approximation of the full-posterior pointwise log predictive density – the same definition loo::loo() reports, and not the p_D of the DIC.

\log \mathrm{CPO}_u^{(2)} exists exactly when \Omega^{-1} + H_u is positive definite (recorded in per_unit$ok) and \mathrm{lpd}_u^{(2)} exactly when \Omega^{-1} - H_u is. A unit failing the former drops every estimate to first order over all units (with a warning), while one failing only the latter contributes its first-order difference to p_loo.

The leverages k_max, k_min, and k_sum read these conditions off the spectrum of -\Omega H_u (k_max < 1, k_min > -1), with k_sum summing across units to the trace form of p_D. p_loo (cross-product form) and p_D (second-derivative form) agree only in the correct-specification limit, and printing a result reports the first-to-second-order gap against its limit p_D/2 as a free check on the Taylor truncation. Because the first-order elpd overstates the truth by \tfrac12 p_D in the limit, keep second_order = TRUE whenever models of different dimension are compared.

type = "auto" resolves to the marginal per-cluster "loco" for two-level fits and per-subject "loso" otherwise. Forcing "loso" on a two-level model scores the conditional predictive of Merkle, Furr & Rabe-Hesketh (2019) instead, and warns. Multigroup units are scored against their own group's implied moments and identified by case number, so compare() pairs them across fits.

The score follows the fitted likelihood's treatment of exogenous covariates, i.e. joint under fixed.x = FALSE, conditional under fixed.x = TRUE (recorded as "joint" or "conditional" in the result's flavour field), and the two flavours are never comparable (compare() refuses to mix them). A single-level fit with conditional.x = TRUE is scored conditionally too: each row by the density of its outcomes given its covariates, from the implied intercepts, slopes and residual covariance of the outcomes. With missing outcomes (missing = "ml") a row is scored on the outcomes it has. These are the scores of the same model fitted with fixed.x = TRUE, conditional.x = FALSE and meanstructure = TRUE (a conditional.x fit always has a mean structure), at the same posterior, and compare() accepts both kinds of fit together.

For composites (⁠<~⁠), lavaan fixes the (co)variances of the indicators at their sample values. Each unit is scored with them recomputed without it (to first order under missing data), so p_loo counts them as parameters.

A random-slope fit (lavaan's rv() modifier; see inlavaan()) is scored leave-one-cluster-out only, conditional on the exogenous covariates (flavour is "conditional").

Supplying theta/Omega evaluates the LOO at an arbitrary Gaussian posterior summary (a singular Omega is restricted to its non-degenerate block), the building block for refit-free submodel scoring. Sigma is the deprecated former name of Omega, still accepted through ... with a warning.

The LOO is stored with the fit when inlavaan()'s test includes "loo" or "waic" (e.g. test = "full"), which also stores the WAIC (see waic()) from the same Taylor pass, or afterwards with add_loo(); loo(fit) with default arguments then returns the stored result. Under the default test = "standard" nothing is stored and loo(fit) computes it on demand. That pass is then kept with the fit, so a later loo(fit) or waic() with default arguments reuses it, with the same numbers and the same warnings.

The Hessian H_u of a row of a single-level model, or of a cluster of a two-level model with complete data, is computed in closed form in the data, with only the second derivatives of the model-implied moments taken by finite differences, once for all units. For the other units (random slopes, two-level models with missing data, rows of a two-level model), H_u is a central difference of the analytic unit scores. Setting options(inlavaan.loo_hessian = "differences") uses the differences for every unit.

The default cores = NULL runs serially, and cores > 1 parallelises the Hessian stage. Supported models are continuous-indicator models fitted with the ML estimator and without sampling weights, single- or two-level, single-group or multigroup, with or without conditional.x = TRUE.

Refused fits. loo() stops with an error for a fit with categorical data or an estimator other than ML, and for a fit with sampling weights (lavaan's sampling.weights argument; the error has class inlavaan_loo_weights). A weighted fit multiplies the log-likelihood of each case by its sampling weight, but the casewise scores have no weights, so they would score another model. waic(), add_loo() and compare(loo = TRUE) refuse the same fits. For a fit with sampling weights, fitMeasures() leaves out a LOO or WAIC measure that is asked for by name, and warns. If no other measure is asked for, it stops with the same error. In fit.measures of compare(), such a measure is NA, with a warning. When the test argument of inlavaan() asks for "loo", "waic" or "full", such a fit warns, skips the LOO and the WAIC, and keeps the reason in get_inlavaan_internal(fit, "test")$skipped. A LOO or a WAIC that an earlier version of INLAvaan stored with a weighted fit is not used.

Accuracy. Against MCMC on four single-level models with 60 to 301 cases, elpd_loo was about 0.5 to 2 above the MCMC value, and the gap per case was larger in the smaller samples. So a difference of about 2 or less between two models can come from the approximation alone. With a mean structure, centre a covariate whose mean lies far from zero before the fit: such a covariate biases the second-order terms, and loo() may not warn. The Accuracy paragraph of waic() gives the details.

Value

An object of class inlavaan_loo: a list with elements

per_unit

Data frame of pointwise results, one row per unit:

unit

Case number for LOSO, cluster position for LOCO.

group

Group membership (multigroup fits only).

nobs

1 for LOSO, the cluster size for LOCO.

l_star

Unit log-likelihood at the summary.

score_norm

Norm of the unit score s_u.

lpd_1, lpd_2

Pointwise log predictive density, at first and second order.

log_cpo_1, log_cpo_2

Pointwise LOO contributions, at first and second order.

det_term

\tfrac12 \log |I + \Omega H_u|, the determinant term of the second-order score.

k_max, k_min, k_sum

Leverage diagnostics (see Details).

k_ssq

\mathrm{tr}[(\Omega H_u)^2], consumed by the closed-form waic() penalty.

ok

Whether the second-order \log \mathrm{CPO} exists.

t_delta

Composite fits only: the drop in \ell_u when the fixed indicator (co)variances are recomputed without the unit, already subtracted from the log CPO terms.

estimates

Matrix with rows elpd_loo, p_loo, looic and columns Estimate, SE, at the highest order available to each.

elpd_1, elpd_2, se_1, se_2, p_loo_1, p_loo_2

First- and second-order aggregates; the second-order ones are NA when any \log \mathrm{CPO}_u^{(2)} does not exist.

elpd_gap, pd_trace

The two sides of the curvature check (see Details); both are NA at first order and partial totals under a units subset.

type, flavour, n_units, n_groups, n_ok, n_lpd_ok, second_order, use_second, theta_overridden

Metadata.

summary() is an alias for print(): it prints the same output and returns the result invisibly.

add_loo() returns a copy of object with the LOO and WAIC results stored alongside the fit (the input object is unchanged); reassign it, e.g. fit <- add_loo(fit). Only the default LOO is stored, so the stored results always match loo(fit) and waic(fit).

References

Alhyari, M., Jamil, H., Montcho, H., & Rue, H. (2026). Deterministic leave-one-cluster-out cross-validation for multilevel Bayesian structural equation models. arXiv:2609.00670. doi:10.48550/arXiv.2609.00670

Merkle, E. C., Furr, D., & Rabe-Hesketh, S. (2019). Bayesian comparison of latent variable models: Conditional versus marginal likelihoods. Psychometrika, 84(3), 802–829. doi:10.1007/s11336-019-09679-0

See Also

fitmeasures(), compare(), inlavaan()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, meanstructure = TRUE)

# Leave-one-subject-out (LOSO) from the single fit -- no refitting
res <- loo(fit)
res
head(res$per_unit)

# Score a submodel without refitting: condition the Laplace summary on the
# visual ~~ speed covariance being zero, then evaluate at that summary
int <- get_inlavaan_internal(fit)
theta <- int$theta_star
Omega <- int$Omega
p <- which(names(coef(fit)) == "visual~~speed")
theta_c <- theta - Omega[, p] * (theta[p] / Omega[p, p])
Omega_c <- Omega - tcrossprod(Omega[, p]) / Omega[p, p]
loo(fit, theta = theta_c, Omega = Omega_c)

# Two-level models are scored per cluster (LOCO) automatically
utils::data("Demo.twolevel", package = "lavaan")
model2l <- "
  level: 1
    fw =~ y1 + y2 + y3
    fw ~ x1 + x2 + x3
  level: 2
    fb =~ y1 + y2 + y3
    fb ~ w1 + w2
"
fit2l <- asem(model2l, Demo.twolevel, cluster = "cluster",
              meanstructure = TRUE, fixed.x = FALSE)
loo(fit2l)


Posterior summaries of the parameters as a data frame

Description

The posterior summary of each parameter of an INLAvaan fit, as a numeric data frame with the rows and the column names of lavaan::parameterEstimates(). Use it for your own tables, or to collect the estimates of many fits in a simulation. summary() prints the same numbers.

Usage

parameterestimates(object, ..., level = 0.95)

parameterEstimates(object, ..., level = 0.95)

Arguments

object

An object of class INLAvaan. Any other object, such as a lavaan or blavaan fit, is passed to lavaan::parameterEstimates() with all its arguments.

...

For an INLAvaan fit: se and ci (FALSE drops the columns), and the arguments of lavaan::parameterEstimates() that choose rows (remove.eq, remove.ineq, remove.system.eq, remove.def, remove.nonfree, remove.unused, remove.step1, remove.aux) and plabel. Arguments that ask for standardised estimates, R-square or other output give an error. zstat, pvalue, boot.ci.type, cov.std, fmi.options and header are accepted, so that code written for lavaan runs, and change nothing: there is never a z or p-value column. For other objects: any argument of lavaan::parameterEstimates().

level

The probability of the equal-tailed credible interval, between 0 and 1. Defaults to 0.95. Give it by name.

Details

Columns

est is the posterior mean, se the posterior standard deviation, and ci.lower and ci.upper the bounds of the equal-tailed credible interval at level. The other columns are those of lavaan::parameterEstimates(): block and group for a model with several groups, block and level for a two-level model, and label when the model has labels. There is no z statistic and no p-value.

as.data.frame() gives a plain data frame. The class lavaan.data.frame only makes print() round the numbers to three decimals.

Where the interval comes from

The interval is equal-tailed: its bounds are the quantiles of the posterior at (1 - \mathrm{level})/2 and (1 + \mathrm{level})/2. A free parameter uses the quantiles of its skew-normal (or normal) marginal. A covariance, a defined (⁠:=⁠) parameter, the variance or intercept of a composite, or an intercept that the fit centres (see centring in inlavaan_control()) uses the skew-normal fitted to its posterior draws, or the quantiles of the draws themselves. The interval is never the mean plus or minus a multiple of the standard deviation. No random numbers are drawn, so the same call always gives the same numbers, and the interval at a lower level lies inside the interval at a higher level.

The bounds of the rows summarised from draws carry Monte Carlo error, which grows as level nears 1, because fewer draws lie in each tail. For such a level, fit the model with a larger nsamp.

Fixed parameters and other rows

A fixed parameter, such as a loading fixed to 1, has the value it is fixed at in est, 0 in se, and both bounds at its value, as in lavaan. An equality constraint such as a == b or a == 0.8 is built into the parameters, so the table has no rows for constraints. A defined parameter that is undefined in almost every draw has NA in every column.

remove.nonfree = TRUE keeps the meaning it has in lavaan: it drops every row that is not a free parameter, so also the scaling parameters and the variances and intercepts of composites, whose posteriors come from the draws. To keep every row that has a posterior spread, keep the rows with se > 0 instead.

The variance and the intercept of a composite hold their posterior means, as summary() shows them. In lavaan::parameterEstimates() they hold the values at the posterior means of the weights.

For a model with random slopes (lavaan's rv()), the level-1 regression that carries a slope is fixed at 0, so it reads 0 in every column. The slope's own rows are at level 2.

lavaan and blavaan

INLAvaan exports parameterEstimates() and parameterestimates(), which mask those of lavaan when INLAvaan is attached after lavaan. A call on any object that is not an INLAvaan fit goes to lavaan::parameterEstimates() with all its arguments, so a lavaan or blavaan fit gets what lavaan gives it. If lavaan is attached after INLAvaan, lavaan's functions mask these, and an INLAvaan fit then gets only the posterior means. Call INLAvaan::parameterestimates() in that case.

Fits from earlier versions

Level 0.95 always works, because it reads the stored summary. Another level needs the posterior draws of the parameters that are summarised from draws with no skew-normal fitted to them (with marginal_method = "gaussian", for example). A fit made by an earlier version did not keep them, so such a call stops. Fit the model again with fit <- update(fit).

Value

A data frame of class c("lavaan.data.frame", "data.frame"), with one row per row of lavaan::parameterEstimates() and these columns, in this order: lhs, op, rhs, then block, level, group, efa and label where lavaan gives them, then est, se, ci.lower and ci.upper, and plabel if asked for. est, se, ci.lower and ci.upper are numeric.

See Also

summary(), standardisedsolution(), coef(), vcov()

Examples

HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(
  HS.model,
  data = HolzingerSwineford1939,
  test = "none",
  nsamp = 100,
  vb_correction = "none",
  silent = TRUE
)

# One row per parameter, with the columns of lavaan::parameterEstimates()
pe <- parameterestimates(fit)
head(pe)

# 90% credible intervals of the free parameters
parameterestimates(fit, level = 0.90, remove.nonfree = TRUE)

# Plain numeric columns for a table of your own
pe <- as.data.frame(pe)
pe[pe$op == "=~", c("lhs", "rhs", "est", "ci.lower", "ci.upper")]

Plot an INLAvaan Object

Description

Generates diagnostic plots for a fitted INLAvaan model.

Usage

## S4 method for signature 'INLAvaan,ANY'
plot(
  x,
  y,
  type = c("marg_pdf", "sn_fit", "sn_fit_log"),
  params = "all",
  nrow = NULL,
  ncol = NULL,
  use_ggplot = TRUE,
  points = FALSE,
  ...
)

Arguments

x

An object of class INLAvaan.

y

Not used.

type

Character. One of "marg_pdf" (default; posterior marginal densities), "sn_fit" (skew-normal fit diagnostic on natural scale), or "sn_fit_log" (same on log scale).

params

Character vector of parameter names to plot, as in coef() or := labels, or "all" (default) to plot all parameters.

nrow, ncol

Integer. Number of rows/columns for the facet grid when use_ggplot = TRUE. If NULL (default), layout is chosen automatically.

use_ggplot

Logical. When TRUE (default) and ggplot2 is available, a ggplot2 object is returned. Set to FALSE for a base-R plot.

points

Logical. When TRUE, individual grid points are overlaid on the curves. Defaults to FALSE.

...

Additional arguments (currently unused).

See Also

diagnostics(), summary()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "none", silent = TRUE)

# Posterior marginal densities (default)
plot(fit)

# Skew-normal fit diagnostic for a single parameter
plot(fit, type = "sn_fit", params = "visual=~x1")



Posterior Predictions for INLAvaan Models

Description

Compute posterior predictions from a fitted INLAvaan model, including latent variable scores, predicted observed values, and imputed missing data.

Usage

## S4 method for signature 'INLAvaan'
predict(
  object,
  type = c("lv", "yhat", "ov", "ypred", "ydist", "ymis", "ovmis"),
  newdata = NULL,
  level = 1L,
  nsamp = 1000,
  ymis_only = FALSE,
  summary = FALSE,
  ...
)

Arguments

object

An object of class INLAvaan.

type

Character string specifying the type of prediction:

"lv"

(default) Posterior draws of latent variable scores \eta | y, \theta. A composite (<~) score is the weighted sum of its indicators (centred without a mean structure).

"yhat", "ov"

Predicted means for observed variables E(y | \eta, \theta) = \nu + \Lambda \eta; no residual noise. An observed outcome is predicted from its regressors, and an indicator of a composite from the composite.

"ypred", "ydist"

Predicted observed values including residual noise y = \nu + \Lambda \eta + \varepsilon, \varepsilon \sim N(0, \Theta), with the residual variances that lavInspect(fit, "theta") reports (observed outcomes included, observed covariates excluded), except that the drawn indicators of a composite keep its weighted sum.

"ymis", "ovmis"

Imputed values for missing observations, drawn from the conditional distribution y_{mis} | y_{obs}, \theta.

newdata

An optional data frame of new observations. If supplied, predictions are computed for newdata rather than the original training data. Not supported for type = "ymis". For a two-level model newdata must hold the cluster variable (and the group variable of a multigroup fit), and its clusters are scored with the fitted parameters.

level

Integer; for type = "lv" in two-level models, specifies whether level 1 or level 2 latent variables are desired (default 1L). Other types ignore it: for two-level models, "yhat" and "ypred" give the total within plus between prediction, and a "ypred" draw keeps its cluster's between-level values, so only the observation-level residuals are new. For a random-slope model (see inlavaan()), each level 2 latent variable, slopes included, is drawn on its own, so draws of different variables are independent given the parameters, and level 1 values are conditional means. Its "yhat" and "ypred" use these empirical Bayes values (closed-form route only), and "ypred" adds the level-1 and between-level residuals.

nsamp

Integer; number of posterior samples to use for prediction. Defaults to 1000.

ymis_only

Logical; only applies when type = "ymis". When TRUE, returns only the imputed values as a named numeric vector per sample (names of the form "varname[rowindex]", matching the blavaan convention). When FALSE (default), returns the full data matrix with missing values filled in.

summary

Logical. When TRUE, collapse the posterior draws with summary() and return summary statistics (mean, SD, quantiles, mode) instead of the raw draws – equivalent to calling summary(predict(object, ...)) but without materialising the intermediate draws object. Default FALSE.

...

Currently unused.

Value

A list of nsamp posterior draws, each a matrix (or data frame, for multiple groups) with rows corresponding to cases and columns to variables or latent factors. When summary = TRUE, instead returns a summary.predict.inlavaan_internal object with the posterior mean, SD, quantiles, and mode for each case/variable.

See Also

sampling(), simulate(), summary()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "none", silent = TRUE)

# Posterior latent variable scores
lv_scores <- predict(fit)
head(lv_scores)

# Predicted observed variable means
yhat <- predict(fit, type = "yhat")
head(yhat)

# Point estimates only, skipping the manual summary() step
predict(fit, type = "yhat", summary = TRUE)



Specify priors for a SEM

Description

Specify priors for a SEM, similar to how blavaan::dpriors() works.

Usage

priors_for(...)

Arguments

...

Named arguments specifying prior distributions for lavaan parameter types.

Details

This function provides a convenient way to specify prior distributions for different types of parameters in a structural equation model (SEM). It uses a registry of default priors for common lavaan parameter types (e.g., loadings, regressions, residuals, etc.) and allows users to override these defaults by passing named arguments.

The parameter names, and default settings, are:

Note that the normal distributions are parameterised using standard deviations, and not variances. For example, normal(0,10) means a normal distribution with mean 0 and standard deviation 10 (not variance 10).

Value

A named character vector of prior specifications, where names correspond to lavaan parameter types (e.g., "lambda", "beta", "theta", etc.) and values are character strings specifying the prior distribution (e.g., "normal(0,10)", "gamma(1,0.5)[sd]", "gamma(1,1)[prec]", etc.).

Scale qualifiers

A prior on a variance parameter (theta, psi) is a normal or a gamma distribution. A qualifier after it states the scale that the prior is on:

The necessary Jacobian adjustment is applied automatically.

A normal prior on a variance, a standard deviation or a precision is truncated at zero, so that it is a proper distribution on the positive values. For example, "normal(0,1)[sd]" is a half-normal prior on the standard deviation.

The qualifiers apply to priors on variances only. A qualifier on any other parameter (a loading, a regression coefficient, an intercept, a threshold, a correlation or covariance, or a composite weight) is an error. A beta prior is for correlations (rho), and a beta prior on a variance is an error.

blavaan reads a gamma prior with no qualifier as a prior on the precision, whereas INLAvaan reads it as a prior on the variance. The qualifiers [var], [sd] and [prec] mean the same in both packages, so use one of them when the same syntax is fitted with both. INLAvaan shows a message, once per session, when a gamma prior on a variance has no qualifier.

See Also

inlavaan(), acfa(), asem(), agrowth()

Examples

priors_for(nu = "normal(0,10)", lambda = "normal(0,1)", rho = "beta(3,3)")

# Precision-scale prior for residual variances (blavaan-style)
priors_for(theta = "gamma(1,1)[prec]")

# Half-normal prior on the standard deviations of the latent variables
priors_for(psi = "normal(0,1)[sd]")

Fast approximation of the skew-normal quantile function

Description

A fast approximation of skew-normal quantiles, from the INLA GMRFLib C source and originally by Thomas Luu (see the references). It needs no iterative inversion, but it is only approximate: use qsnorm() for accurate quantiles.

Usage

qsnorm_fast(p, xi = 0, omega = 1, alpha = 0)

Arguments

p

Vector of probabilities.

xi

Location parameter.

omega

Scale parameter, positive.

alpha

Shape parameter.

Details

The domain is split into tail regions, handled through the Lambert W function, and a central region, handled by a fifth-order Taylor expansion of the inverse error function about a well-chosen expansion point. Negative alpha is handled by the symmetry Q(u; -\alpha) = -Q(1 - u; \alpha). qsnorm() uses it only as the start of Newton's method.

The errors below are in units of omega, for a tail probability (p or 1 - p), and were measured for alpha in [-30, 30]. The result is exact for alpha = 0. For alpha of \pm 1, where the quantile has a closed form, it is exact except far in the heavy tail, where 1 - p or sqrt(p) rounds: the error is about 2e-8 at a tail probability of 1e-9, 2e-3 at 1e-14 and 0.1 at 1e-16. For other alpha, the error against qsnorm() is at most about 7e-3 for p in [0.01, 0.99]. It is largest for a tail probability near 1e-3 (about 0.085) and smaller further out: 0.02 to 0.04 from 1e-15 to 1e-8, and up to 0.06 below 1e-15, where 1 - p rounds. The exception is the light tail (the lower tail when alpha > 0, the upper tail when alpha < 0) for alpha within about 0.015 of \pm 2.18, where the fifth-order coefficient of the expansion is 0. There the error grows further out: about 0.36 at a tail probability of 1e-9, 1.1 at 1e-13 and 2.1 at 1e-16. For most alpha < 0, a p below about 1e-16 gives -Inf, and for most alpha > 0, a p within about 1e-16 of 1 gives Inf.

Value

A numeric vector of approximate quantiles. The arguments are recycled to the length of the longest, and an argument of length zero gives a zero-length result. p of 0 and 1 give -Inf and Inf.

References

Luu, T. (2016). Fast and accurate parallel computation of quantile functions for random number generation (Doctoral thesis). UCL (University College London). https://discovery.ucl.ac.uk/1482128/

See Also

qsnorm() for accurate quantiles.

Examples

qsnorm_fast(c(0.025, 0.5, 0.975))
qsnorm_fast(c(0.025, 0.5, 0.975), xi = 2, omega = 0.5, alpha = 1)

# The error of the approximation, in units of omega
p <- c(0.025, 0.5, 0.975)
qsnorm_fast(p, alpha = 3) - qsnorm(p, alpha = 3)

Model Residuals for INLAvaan Models

Description

Extract the difference between the observed and model-implied (fitted) sample statistics from a fitted INLAvaan model. As in lavaan and blavaan, residuals are computed at the parameter estimates – here the posterior means – not as a posterior distribution over residuals.

Usage

## S4 method for signature 'INLAvaan'
residuals(object, type = "raw", labels = TRUE, ..., per_cluster = FALSE)

## S4 method for signature 'INLAvaan'
resid(object, type = "raw", ..., per_cluster = FALSE)

Arguments

object

An object of class INLAvaan.

type

Character. "raw" (default) returns the unscaled difference between the observed and model-implied covariance matrix (and mean vector, when a mean structure is present). "cor" (or "cor.bollen") first rescales both matrices to a correlation matrix. "cor.bentler" rescales both by the observed variances (the basis of the SRMR). "normalized" and "standardized" divide the raw residuals by their asymptotic standard errors. "casewise" (aliases "case", "obs", "observations", "ov") returns observed-minus-fitted values for each observation.

labels

Logical. Attach variable names to the output. Default TRUE.

...

Currently unused.

per_cluster

Logical. For a random-slope model, return the residuals of each cluster instead of the averaged ones. Default FALSE.

Details

This delegates to lavaan's own residuals() machinery, so the return structure matches lavaan exactly. Because INLAvaan stores the posterior means as the point estimates of the fitted object, the residuals are the observed statistics minus the posterior-mean model-implied statistics (mirroring blavaan, which likewise inherits lavaan's residuals() without overriding it).

For a model with random slopes (lavaan's rv()), the residuals compare the sample moments with the averaged moments of fitted(). With per_cluster = TRUE, they compare each cluster's sample mean and within-cluster covariance with its expected ones. A covariance of two variables observed together in fewer than two rows of a cluster is NA. The raw and correlation types are available, and type = "casewise" gives the observed values minus the outcomes' means given the covariates (closed-form route only).

Value

For moment-based types, a list with elements type, cov, and (when relevant) mean. For type = "casewise", a numeric matrix of observed-minus-fitted values.

See Also

fitted(), predict(), fitMeasures()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "none", silent = TRUE)

# Raw residual covariance matrix (posterior means)
residuals(fit)

# SRMR-basis residuals
residuals(fit, type = "cor.bentler")

# Casewise observed-minus-fitted values
head(residuals(fit, type = "casewise"))



Draw Samples from the Generative Model

Description

Sample model parameters, latent variables, or observed variables from the generative model underlying a fitted INLAvaan model. By default, parameters are drawn from the posterior distribution; set prior = TRUE to draw from the prior instead (useful for prior predictive checks).

Usage

sampling(object, ...)

## S4 method for signature 'INLAvaan'
sampling(
  object,
  type = c("lavaan", "theta", "latent", "observed", "implied", "all"),
  nsamp = 1000L,
  samp_copula = NULL,
  prior = FALSE,
  silent = FALSE,
  ...
)

Arguments

object

An object of class INLAvaan (or inlavaan_internal).

...

Additional arguments (currently unused).

type

Character string specifying what to sample:

"lavaan"

(Default) The lavaan-side (constrained) model parameters. Returns an nsamp by npar matrix.

"theta"

The INLAvaan-side unconstrained parameters. Returns an nsamp by npar matrix. An intercept that the fit centres appears in its centred coordinate (see centring in inlavaan_control()).

"latent"

Latent variables from the model-implied distribution. Returns an nsamp by nlv matrix (one draw per posterior sample, not tied to any individual). For two-level models the matrix holds the within- and between-level latent variables, the level-2 columns carrying the .l2 suffix when the same latent variable also exists at level 1.

"observed"

Observed variables generated from the full model. Returns an nsamp by nobs_vars matrix. For two-level models each row is a draw from the two-level generative model, \mathbf{y} = \mathbf{y}^B + \mathbf{y}^W: variables that live at both levels sum their between- and within-level draws, and within-only or between-only variables take the single level available to them.

"implied"

Model-implied moments. Returns a length-nsamp list, each element a list with cov (model-implied covariance matrix) and, when meanstructure = TRUE, mean (model-implied mean vector). For multi-group models each element is itself a list of groups. For two-level models each element is a list with a within and a cluster block, each holding a cov and a mean, as lavaan::lavInspect() reports them.

"all"

A named list with elements lavaan, theta, latent, observed, and implied.

nsamp

Number of samples to draw.

samp_copula

[Deprecated] Has no effect. The draws always couple the fitted marginals by a Gaussian copula, as the draws of the fit do. For a fit with marginal_method = "gaussian" they are the draws of the Laplace approximation.

prior

Logical. When TRUE, parameters are drawn from the prior distribution and then propagated through the generative model. When FALSE (default), parameters come from the posterior.

silent

Logical. When TRUE, suppresses the informational message about rejected non-PD draws during prior rejection sampling. Default FALSE.

Details

Each row of the output corresponds to a fresh parameter draw: a new \boldsymbol\theta^{(s)} is sampled and then propagated through the generative chain to produce one latent vector and one observed vector. This makes sampling() ideal for prior and posterior predictive checks (e.g., density overlays, test statistic distributions).

The generative chain is:

\boldsymbol\theta^{(s)} \sim \pi(\boldsymbol\theta \mid \mathbf{y})

\boldsymbol\eta^{(s)} \sim N((\mathbf{I} - \mathbf{B})^{-1}\boldsymbol\alpha,\,\boldsymbol\Phi)

\mathbf{y}^{*(s)} \sim N(\boldsymbol\Lambda\boldsymbol\eta^{(s)} + \boldsymbol\nu,\,\boldsymbol\Theta)

If you need complete replicate datasets (many observations from a single parameter draw) — for example, for simulation-based calibration (SBC) — use simulate() instead.

This is distinct from predict(), which computes individual-specific factor scores \boldsymbol\eta \mid \mathbf{y},\boldsymbol\theta conditional on observed data.

For a random-slope model, each draw takes the level-2 variables, slopes included, first and puts the drawn slopes into their level-1 paths, and type = "implied" gives the moments averaged over the covariates (see fitted()). As for other models, the covariates of a latent or observed draw come from their fitted moments, whereas simulate() keeps the observed covariates of a random-slope model.

Value

A matrix or named list, depending on type.

See Also

simulate() for generating complete replicate datasets (e.g., for SBC); predict() for individual-specific factor scores; bfit_indices() for Bayesian fit indices.

Examples

utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa("visual =~ x1 + x2 + x3", HolzingerSwineford1939)

# Posterior samples of lavaan-side parameters
samps <- sampling(fit, nsamp = 500)
head(samps)

# Prior predictive samples
y_prior <- sampling(fit, type = "observed", nsamp = 500, prior = TRUE)

Simulate Datasets from the Generative Model

Description

Generate complete synthetic datasets from a fitted INLAvaan model. For each simulation, a single parameter vector is drawn (from the posterior or prior), and then sample.nobs observations are generated from the model-implied distribution at that parameter value.

Usage

## S4 method for signature 'INLAvaan'
simulate(
  object,
  nsim = 1L,
  seed = NULL,
  sample.nobs = NULL,
  prior = FALSE,
  samp_copula = NULL,
  silent = FALSE,
  ...
)

Arguments

object

An object of class INLAvaan.

nsim

Number of replicate datasets to generate (default 1).

seed

Optional random seed (passed to set.seed()).

sample.nobs

Number of observations per dataset, per group for multigroup models (a single number is used for every group). Defaults to the sample size of the original data.

prior

Logical. When TRUE, parameters are drawn from the prior; when FALSE (default), from the posterior.

samp_copula

[Deprecated] Has no effect. The posterior draws always couple the fitted marginals by a Gaussian copula, as the draws of the fit do.

silent

Logical. When TRUE, suppresses the informational message about rejected non-PD draws. Default FALSE.

...

Additional arguments (currently unused).

Details

This function is designed for tasks that require full replicate datasets from a single parameter draw, such as simulation-based calibration (SBC) and posterior predictive p-values. It differs from sampling() which generates one observation per parameter draw (useful for prior/posterior predictive density overlays).

For each simulation s = 1, \ldots, S:

  1. Draw \boldsymbol\theta^{(s)} from the posterior (or prior).

  2. Compute the model-implied covariance \boldsymbol\Sigma(\boldsymbol\theta^{(s)}). If it is not positive-definite, reject and redraw.

  3. Generate a dataset of sample.nobs rows from N(\boldsymbol\mu(\boldsymbol\theta^{(s)}),\, \boldsymbol\Sigma(\boldsymbol\theta^{(s)})).

Parameter draws reuse the same internal machinery as sampling() (sample_params_prior / sample_params_posterior), so the prior specification is consistent.

A two-level dataset keeps the clusters of the data, with their labels and sizes, unless sample.nobs is given. For a random-slope model (closed-form route only), each cluster keeps its own covariates and size, its slopes and other level-2 effects are drawn first, and then its outcomes. sample.nobs is not available. Other models draw their covariates from their fitted moments.

Value

A list of length nsim. Each element is a data frame with sample.nobs rows and two attributes:

See Also

sampling() for single-observation draws from the predictive distribution (prior/posterior predictive checks).

Examples

utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa("visual =~ x1 + x2 + x3", HolzingerSwineford1939)

# Simulate one replicate dataset from the posterior
sims <- simulate(fit, nsim = 1)
head(sims[[1]])                    # data frame
attr(sims[[1]], "truth")           # true lavaan-side (x-space) parameters
attr(sims[[1]], "truth_theta")     # corresponding unconstrained (theta-space) parameters

# Simulate from the prior (e.g., for SBC)
sims_prior <- simulate(fit, nsim = 5, prior = TRUE)
lapply(sims_prior, nrow)

Standardised solution of a latent variable model

Description

Standardised solution of a latent variable model

Usage

standardisedsolution(
  object,
  type = "std.all",
  se = TRUE,
  ci = TRUE,
  level = 0.95,
  postmedian = FALSE,
  postmode = FALSE,
  cov.std = TRUE,
  remove.eq = TRUE,
  remove.ineq = TRUE,
  remove.def = FALSE,
  nsamp = 250,
  ...
)

standardisedSolution(
  object,
  type = "std.all",
  se = TRUE,
  ci = TRUE,
  level = 0.95,
  postmedian = FALSE,
  postmode = FALSE,
  cov.std = TRUE,
  remove.eq = TRUE,
  remove.ineq = TRUE,
  remove.def = FALSE,
  nsamp = 250,
  ...
)

standardizedsolution(
  object,
  type = "std.all",
  se = TRUE,
  ci = TRUE,
  level = 0.95,
  postmedian = FALSE,
  postmode = FALSE,
  cov.std = TRUE,
  remove.eq = TRUE,
  remove.ineq = TRUE,
  remove.def = FALSE,
  nsamp = 250,
  ...
)

standardizedSolution(
  object,
  type = "std.all",
  se = TRUE,
  ci = TRUE,
  level = 0.95,
  postmedian = FALSE,
  postmode = FALSE,
  cov.std = TRUE,
  remove.eq = TRUE,
  remove.ineq = TRUE,
  remove.def = FALSE,
  nsamp = 250,
  ...
)

Arguments

object

An object of class INLAvaan.

type

Character (dots and underscores are interchangeable: "std.all" and "std_all" are the same type). If "std_lv", the standardized estimates are based on the variances of the (continuous) latent variables only. If "std_all", the standardized estimates are based on the variances of both (continuous) observed and latent variables. If "std_nox", the standardized estimates are based on the variances of both (continuous) observed and latent variables, but not the variances of exogenous covariates. Note that "std_nox" only differs from "std_all" if fixed_x = TRUE; if fixed_x = FALSE, the exogenous covariates are treated as random variables (and standardized) just like any other variable, and a warning is issued. Alternatively, type may be a vector of (observed) variable names (for example type = c("x1", "x2")); in that case only the parameters involving these variables are standardized (the other observed variables are left unstandardized). This is a generalization of "std_nox", where the (observed) exogenous x variables are the ones left unstandardized.

se

Logical. If TRUE, standard errors for the standardized parameters will be computed, together with a z-statistic and a p-value.

ci

If TRUE, confidence intervals are added to the output.

level

The confidence level required.

postmedian

Logical; if TRUE, include posterior median in estimates.

postmode

Logical; if TRUE, include posterior mode in estimates.

cov.std

Logical. If TRUE, the (residual) observed covariances are scaled by the square root of the Theta diagonal elements, and the (residual) latent covariances are scaled by the square root of the Psi diagonal elements. If FALSE, the (residual) observed covariances are scaled by the square root of the diagonal elements of the model-implied observed covariance matrix, and the (residual) latent covariances are scaled similarly using the model-implied covariance matrix of the latent variables. Documented explicitly here (rather than inherited) because lavaan >= 0.7-1 renamed this and the next three arguments to snake_case.

remove.eq

Logical. If TRUE, filter the output by removing all rows containing equality constraints, if any.

remove.ineq

Logical. If TRUE, filter the output by removing all rows containing inequality constraints, if any.

remove.def

Logical. If TRUE, filter the output by removing all rows containing parameter definitions, if any.

nsamp

The number of samples to draw from the approximate posterior distribution for the calculation of standardised estimates.

...

Additional arguments sent to lavaan::standardizedSolution().

Details

For a model with random slopes (lavaan's rv()), the estimates are scaled by the implied variances averaged over the covariates, which include the mean and the variance of each slope. The level-1 row that carries a slope gives the standardised mean slope. The slope's own rows are on the same standardised-slope scale: its intercept is a standardised slope, and its (residual) variance is the share of the outcome's level-1 variance that the slope's (residual) variation adds.

Value

A data.frame containing standardised model parameters.

See Also

summary(), coef(), vcov()

Examples

HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
"
utils::data("HolzingerSwineford1939", package = "lavaan")

# Fit a CFA model with standardised latent variables
fit <- acfa(
  HS.model,
  data = HolzingerSwineford1939,
  test = "none",
  nsamp = 10,
  vb_correction = "none",
  silent = TRUE
)
standardisedsolution(fit, nsamp = 10, se = FALSE, ci = FALSE)

Timing Information for INLAvaan Models

Description

Extract wall-clock timings for individual computation stages of a fitted INLAvaan model.

Usage

timing(object, ...)

## S4 method for signature 'INLAvaan'
timing(object, what = "total", ...)

Arguments

object

An object of class INLAvaan.

...

Currently unused.

what

Character vector of timing segment names to return, or "all" to return every segment. Defaults to "total". Available segments (depending on model options): "init" (which includes the lavaan model setup), "optim" (the search for the posterior mode and the Laplace approximation), "vb" (the VB correction), "loglik", "marginals" (the marginals and the checks of the fit), "norta", "sampling", "covariances", "definedpars", "test", "loo", "waic", "total". The segments are disjoint and "total" is their sum. "norta" is about 0: the draws no longer adjust the correlations of their copula (NORTA), and the segment is kept so that code that asks for it still works. "loo" and "waic" are recorded only when the fit computed them, i.e. test (see inlavaan()) included "loo", "waic" or "full" and the model is supported (see loo()); requesting either otherwise gives an error explaining why, distinct from requesting a misspelled segment name.

Value

A named numeric vector (class c("timing.INLAvaan", "numeric")) of elapsed times in seconds. Printing formats short durations as seconds, longer ones as minutes or hours.

See Also

diagnostics(), summary()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "none", silent = TRUE)

# Total elapsed time
timing(fit)

# All stages
timing(fit, what = "all")

# Specific stages
timing(fit, what = c("optim", "marginals"))



Update and re-fit an INLAvaan model

Description

Re-fit an INLAvaan model with modified arguments, in the style of stats::update(). This is convenient for prior-sensitivity analyses (vary dp or the prior() modifiers), iterative respecification (swap the model or add syntax), and swapping approximation settings (e.g. marginal_method, nsamp) without retyping the whole call.

Usage

## S4 method for signature 'INLAvaan'
update(object, model, add, ..., evaluate = TRUE)

Arguments

object

An object of class INLAvaan.

model

Optional replacement model, in the same form accepted by inlavaan() (lavaan model syntax or a parameter table).

add

Optional lavaan syntax appended to the original model. Requires the original model to have been specified as a syntax string, and is ignored when model is supplied.

...

Further arguments passed to inlavaan(), overriding the values in the original call (e.g. dp, marginal_method, nsamp, data).

evaluate

Logical. If TRUE (default) the updated call is evaluated and the re-fitted INLAvaan object is returned; if FALSE the updated, unevaluated call is returned for inspection.

Details

The method edits the recorded inlavaan() call, replacing model (or extending it via add) and overriding any argument supplied through ..., then re-evaluates it. Because INLAvaan extends the lavaan class, a dedicated method is required: without it, update() would dispatch to lavaan's method and silently return a frequentist lavaan fit instead of a Bayesian one.

When the parameter structure and the data are preserved (no change to model, add, model.type, data or the sample statistics), the previous posterior mode is passed as the optimiser's starting value (a warm start), so mode-finding is typically much faster than a cold fit. This makes prior sweeps particularly cheap. The warm start changes the optimiser's starting point, so the mode it finds agrees with that of a fresh fit only up to the optimiser's tolerance (differences of order 1e-5 on the internal scale). A fit that fails the check of the one-step VB correction is the exception. The warm search for the mode costs less, and so lowers the cap that vb_budget sets on the VB solve (see inlavaan_control()). The solve can then stop further short of the VB mean than in a fresh fit, and the VB mean and the log marginal likelihood differ more. Give start = NULL for the fit of a fresh call, or control = list(vb_budget = Inf) to lift the cap. It is used only when the refitted model has the same free parameters, by name and in the same order. Otherwise, as after std.lv = TRUE or meanstructure = TRUE, the fit starts from the usual values. It is not used when the recorded data are a function call, such as lavaan::simulateData(...) or read.csv(...), which can give other data each time, rather than an object or a part of one (dd, dd[dd$g == 1, ]). Supply start explicitly to override it, or start = NULL to start from the usual values and get the fit of a fresh call.

The refit needs the objects that the recorded call names: the data, the model, and the sample statistics of a fit to summary data (sample.cov, sample.mean, sample.nobs). When one of them is no longer found, as after rm(dd) or in a new session, update() stops with an error of class inlavaan_update_data_not_found that names it. Give it again, as in update(fit, data = dd) or update(fit, model = mm), or fit the model again with inlavaan(). An object named after a function, such as df or data in a new session, counts as not found. A data call, such as simulateData(mm, sample.nobs = 100), is not run before the refit: only the object at its root (mm) is checked. An error inside the call is the error of the refit.

update(fit, arg = NULL) drops arg from the recorded call, as stats::update() does. An argument given under another spelling that lavaan reads as the same, such as std_ov for std.ov, replaces the recorded one, and std_ov = NULL drops it. An abbreviated argument name, such as dat for data, is not completed: update() stops with an error of class inlavaan_update_abbreviated that names the arguments it may mean.

verbose = TRUE and silent = TRUE cannot go together. So update(fit, silent = TRUE) drops verbose from the recorded call, and update(fit, verbose = TRUE) drops silent.

Fits produced by INLAvaan versions that did not record their call cannot be updated; re-fit once with inlavaan() (or acfa(), asem(), agrowth()) and update() will work on the new object.

Value

A re-fitted INLAvaan object, or the updated call when evaluate = FALSE.

See Also

inlavaan(), compare()

Examples

## Not run: 
model <- "visual =~ x1 + x2 + x3"
fit <- acfa(model, data = lavaan::HolzingerSwineford1939)

# Prior sensitivity: refit under a tighter loading prior (warm-started)
fit2 <- update(fit, dp = priors_for(lambda = "normal(0,1)"))

# Respecify: add a residual covariance
fit3 <- update(fit, add = "x1 ~~ x2")
compare(fit, fit3)

# Swap approximation settings only
fit4 <- update(fit, marginal_method = "gaussian", nsamp = 4000)

## End(Not run)

Variance-Covariance Matrix for INLAvaan Models

Description

Extract the posterior variance-covariance matrix of model parameters from a fitted INLAvaan model.

Usage

## S4 method for signature 'INLAvaan'
vcov(object, type = c("lavaan", "theta"), ...)

Arguments

object

An object of class INLAvaan.

type

Character. "lavaan" (default) returns the posterior covariance matrix of the model parameters computed from posterior samples, with one row per entry of coef() (matching lavaan output). "theta" returns the Laplace approximation covariance in the internal parameterisation, with one row per distinct free parameter. An intercept that the fit centres is in its centred coordinate there (see centring in inlavaan_control()).

...

Currently unused.

Value

A square numeric matrix.

See Also

summary(), coef(), standardisedsolution()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, std.lv = TRUE, nsamp = 100,
            test = "none", silent = TRUE)

# Default: posterior covariance of lavaan parameters
vcov(fit)

# Internal parameterisation (Laplace approximation)
vcov(fit, type = "theta")



Widely Applicable Information Criterion for INLAvaan Models

Description

Computes the WAIC of a fitted INLAvaan model in closed form from the fit's Laplace summary – the same per-unit Taylor quantities behind loo(), with no posterior draws and no Monte Carlo error. Single-level models are scored per subject; two-level models are scored per cluster by default, matching the units used by loo(). For a two-level model type = "loso" instead scores the conditional (leave-one-unit-out) WAIC; see Details.

Usage

waic(x, ...)

## S3 method for class 'INLAvaan'
waic(
  x,
  type = c("auto", "loso", "loco"),
  units = NULL,
  second_order = TRUE,
  cores = NULL,
  verbose = FALSE,
  ...
)

## S3 method for class 'inlavaan_internal'
waic(
  x,
  type = c("auto", "loso", "loco"),
  units = NULL,
  second_order = TRUE,
  cores = NULL,
  verbose = FALSE,
  ...
)

## S3 method for class 'inlavaan_waic'
print(x, ...)

## S3 method for class 'inlavaan_waic'
summary(object, ...)

Arguments

x

A fitted INLAvaan object (or its inlavaan_internal list).

...

Not used.

type

Unit type: "auto" (default) resolves to per-subject for single-level models and per-cluster (marginal WAIC) for two-level models. "loso" on a two-level model scores the conditional (leave-one-unit-out) WAIC instead (with a warning; see Details); "loco" cannot be forced on a model without clusters.

units

Optional integer vector of unit indices to score; defaults to all units.

second_order

Logical; include the second-order (Hessian) terms (default TRUE). FALSE gives the first-order WAIC, which equals the first-order LOO exactly – and inherits its bias: a first-order score overstates the elpd by \tfrac12 p_D in the limit, so candidates of different dimension cannot be compared on it (see loo()).

cores

Number of cores for differentiating the unit scores. The default NULL runs serially; parallelism must be requested explicitly.

verbose

Logical; print progress (default FALSE).

object

A fitted INLAvaan object, or an inlavaan_waic result.

Details

Writing \ell_u(\theta) = \log p(y_u \mid \theta) and expanding it to second order about \theta^*, with the posterior taken as N(\theta^*, \Omega), both WAIC terms are available in closed form. \theta^* is the mode moved by the VB correction (see vb_correction in inlavaan()), the same centre as in loo(). The pointwise log predictive density \mathrm{lpd}_u is the same Gaussian integral loo() computes, and the penalty is the polynomial

p_{\mathrm{waic},u} = \mathrm{Var}[\ell_u(\theta)] = s_u^\top \Omega\, s_u + \tfrac12 \mathrm{tr}\!\left[(H_u \Omega)^2\right],

with s_u and H_u the unit's score and Hessian. Then \mathrm{elpd}_{\mathrm{waic}} = \sum_u (\mathrm{lpd}_u - p_{\mathrm{waic},u}) and \mathrm{WAIC} = -2\, \mathrm{elpd}_{\mathrm{waic}}.

Existence. p_{\mathrm{waic},u} is a polynomial in the posterior moments, so unlike the lpd and log CPO integrals of loo() it is finite for every unit and carries no condition of its own. The second-order WAIC therefore exists exactly where its lpd term does: where \Omega^{-1} - H_u is positive definite, equivalently k_{\min} > -1 for the spectrum k of -\Omega H_u. The log CPO condition k_{\max} < 1 is irrelevant here, since the WAIC reads no case-deletion term: a unit whose deleted posterior is improper can still carry an exact second-order WAIC. Where the lpd term fails, every estimate is reported at first order over all units and warns – \mathrm{elpd}_{\mathrm{waic}} is a headline predictive score, and mixing two Taylor orders within one reported number is exactly what loo() refuses for \mathrm{elpd}_{\mathrm{loo}} (the mixed alternative is reserved for p_loo, a secondary diagnostic). That fallback is exact rather than merely lower-order: the identity \mathrm{lpd}^{(1)}_u - p^{(1)}_{\mathrm{waic},u} = \log \mathrm{CPO}^{(1)}_u holds pointwise, so the first-order WAIC is the first-order LOO score. No other threshold is applied: as in loo(), existence is the only condition the package acts on.

The same model restrictions as loo() apply. waic() stops with an error for a fit with categorical data or an estimator other than ML, and for a fit with sampling weights (lavaan's sampling.weights argument; the error has class inlavaan_loo_weights), whose weighted log-likelihood the casewise scores do not follow. The flavour rule applies too: fits with fixed.x = TRUE or conditional.x = TRUE are scored conditionally on the exogenous covariates, fits with fixed.x = FALSE jointly (see loo()). For composites, p_{\mathrm{waic}} also counts the indicator (co)variances that lavaan fixes at their sample values, as p_loo does.

Accuracy. The WAIC and the LOO were checked against MCMC (blavaan, with the same stated priors) on four single-level models with 60 to 301 cases, each fitted with and without a mean structure: the three-factor model of HolzingerSwineford1939, a two-factor model on 60 of its rows, the Political Democracy model, and a two-factor model with a covariate (centred when the model has a mean structure). On every model, elpd_waic and elpd_loo were about 0.5 to 2 above the MCMC values, and p_waic was a little lower. The gap per case was larger in the smaller samples. So a difference in elpd of about 2 or less between two models can come from the approximation alone; compare such models with MCMC if the choice matters. With a mean structure, a covariate whose mean lies several of its standard deviations away from zero makes the intercepts, the loadings and the slopes strongly correlated, and their posterior curved. The second-order terms are then biased, by several units of elpd in the model tested, and neither waic() nor loo() warns (the fit itself may warn; see diagnostics()). Further from zero, some units have no second-order term, and the estimates fall to first order with a warning. Centring such a covariate (subtracting its mean) before the fit avoids this, and changes only the meaning of the intercepts.

Marginal vs conditional WAIC (two-level models). The default per-cluster scoring is the marginal WAIC, which corresponds to leave-one-cluster-out cross-validation – prediction for a new cluster. Setting type = "loso" scores the conditional WAIC, corresponding to leave-one-unit-out – prediction for a new observation within an observed cluster. The two answer different questions and are easily conflated (Merkle, Furr & Rabe-Hesketh, 2019); the per-cluster marginal is the usual model-comparison target, so it is the default, and type = "loso" warns. This matches loo(type = "loso") – the two read the same estimand off the same expansion.

When inlavaan()'s test includes "loo" or "waic" (e.g. test = "full"), the WAIC is derived at fit time from the same Taylor pass as the LOO at no extra cost and stored with the fit: waic(fit) then returns the stored result when called with default arguments, and fitmeasures() reports waic, p_waic, se_waic as part of "all" for free. Under the default test = "standard" nothing is stored and waic(fit) computes it on demand, or reuses the pass of an earlier loo(fit), which is kept with the fit. If the loo package is attached it masks this generic, but dispatch on INLAvaan objects continues to work.

Value

An object of class inlavaan_waic: a list with per_unit (pointwise lpd, p_waic, elpd_waic, with the same unit/group identification as loo()), estimates (matrix with rows elpd_waic, p_waic, waic and columns Estimate, SE), type, flavour, n_units, n_groups, n_lpd_ok (units whose second-order lpd exists), second_order (whether it was requested) and use_second (whether it was used). summary() is an alias for print(): it prints the same output and returns the result invisibly.

See Also

loo(), fitmeasures()

Examples


HS.model <- "
  visual  =~ x1 + x2 + x3
  textual =~ x4 + x5 + x6
  speed   =~ x7 + x8 + x9
"
utils::data("HolzingerSwineford1939", package = "lavaan")
fit <- acfa(HS.model, HolzingerSwineford1939, meanstructure = TRUE)
waic(fit)