| 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 |
| 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
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
-
acfa(): Approximate Confirmatory Factor Analysis. -
asem(): Approximate Structural Equation Modelling. -
agrowth(): Approximate Latent Growth Curve models.
Model specifications
Supports advanced 'lavaan' syntax features, including:
Equality constraints (shared labels,
group.equal,a == banda == <number>)Defined parameters (e.g.,
:=operator for indirect effects)Flexible prior specifications
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.
Summaries and parameter estimates:
summary(),coef(),vcov(),standardisedsolution()Fit assessment and model comparison:
fitmeasures(),bfit_indices(),compare(),diagnostics(),timing()Posterior inference and simulation:
predict(),sampling(),simulate()Visualisation:
plot()
Online vignettes
The package website contains comprehensive examples covering:
Confirmatory Factor Analysis (CFA)
Structural Equation Models (SEM)
Latent Growth Curve Models
Multigroup and Invariance Testing
Mediation Analysis
Author(s)
Maintainer: Haziq Jamil haziq.jamil@gmail.com (ORCID) [copyright holder]
Authors:
Haziq Jamil haziq.jamil@gmail.com (ORCID) [copyright holder]
Other contributors:
Håvard Rue (ORCID) (Statistical and computational methodology) [contributor]
Alvin Bong (Initial site build) [contributor]
Alexandre B. Simas (Tests) [contributor]
Thomas Luu (Skew-normal quantile approximation (Apache License 2.0)) [copyright holder]
See Also
Useful links:
Report bugs at https://github.com/haziqj/INLAvaan/issues
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 |
... |
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 |
estimates |
Logical; if TRUE, print parameter estimates table. Its
numbers are those of |
ci |
Logical. If TRUE (default), show the equal-tailed credible
interval at |
standardized |
Logical; if TRUE, include standardized estimates. |
standardised |
Alias of |
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
externalA list containing an
inlavaan_internalobject.
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
|
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 |
dp |
Default prior distributions for the different types of model
parameters; a named character vector as returned by |
test |
Character vector naming the post-estimation quantities to
compute and store with the fit. The atoms are |
vb_correction |
The variational Bayes (VB) correction of the posterior
mean of the Laplace approximation. |
marginal_method |
How the marginal posterior of each parameter is
approximated. |
marginal_scan |
How the scan behind each skew-normal marginal is taken.
|
marginal_laplace_fallback |
Logical. Rescan with
|
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 |
cov_as_cor |
Logical. Residual and latent-disturbance covariance
parameters ( |
sn_fit_sample |
Logical. When |
control |
A list of tuning settings, made by |
verbose |
Logical. With |
silent |
Logical. Print nothing at all, and muffle the warnings and
messages raised during the fit? Default |
cores |
A positive whole number or |
ppp_method |
How the PPP of a two-level model scores the observed and
the replicate data against the saturated model. |
ppp_nsamp |
The number of posterior draws, each with one replicate data
set, that the PPP of a two-level model uses. Defaults to |
wiggle |
Equality constraints to relax into approximate ones, as in
blavaan. |
wiggle.sd |
The standard deviation of the normal priors that |
n_qmc |
|
vb_method |
|
marginal_correction |
|
samp_copula |
|
samp_norta |
|
sn_fit_ngrid |
|
sn_fit_logthresh |
|
sn_fit_temp |
|
debug |
|
add_priors |
|
optim_method |
|
numerical_grad |
|
hessian_method |
|
... |
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:
-
int.ov.free = TRUE -
int.lv.free = FALSE -
auto.fix.first = TRUE(unlessstd.lv = TRUE) -
auto.fix.single = TRUE -
auto.var = TRUE -
auto.cov.lv.x = TRUE -
auto.efa = TRUE -
auto.th = TRUE -
auto.delta = TRUE -
auto.cov.y = TRUE -
auto.cov.rv = FALSE, where lavaan knows the option: a random slope is not correlated with the other random effects of the between level, as in lavaan 0.7-3 and earlier
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
|
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 |
dp |
Default prior distributions for the different types of model
parameters; a named character vector as returned by |
test |
Character vector naming the post-estimation quantities to
compute and store with the fit. The atoms are |
vb_correction |
The variational Bayes (VB) correction of the posterior
mean of the Laplace approximation. |
marginal_method |
How the marginal posterior of each parameter is
approximated. |
marginal_scan |
How the scan behind each skew-normal marginal is taken.
|
marginal_laplace_fallback |
Logical. Rescan with
|
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 |
cov_as_cor |
Logical. Residual and latent-disturbance covariance
parameters ( |
sn_fit_sample |
Logical. When |
control |
A list of tuning settings, made by |
verbose |
Logical. With |
silent |
Logical. Print nothing at all, and muffle the warnings and
messages raised during the fit? Default |
cores |
A positive whole number or |
ppp_method |
How the PPP of a two-level model scores the observed and
the replicate data against the saturated model. |
ppp_nsamp |
The number of posterior draws, each with one replicate data
set, that the PPP of a two-level model uses. Defaults to |
wiggle |
Equality constraints to relax into approximate ones, as in
blavaan. |
wiggle.sd |
The standard deviation of the normal priors that |
n_qmc |
|
vb_method |
|
marginal_correction |
|
samp_copula |
|
samp_norta |
|
sn_fit_ngrid |
|
sn_fit_logthresh |
|
sn_fit_temp |
|
debug |
|
add_priors |
|
optim_method |
|
numerical_grad |
|
hessian_method |
|
... |
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:
-
meanstructure = TRUE -
int.ov.free = FALSE -
int.lv.free = TRUE -
auto.fix.first = TRUE(unlessstd.lv = TRUE) -
auto.fix.single = TRUE -
auto.var = TRUE -
auto.cov.lv.x = TRUE -
auto.efa = TRUE -
auto.th = TRUE -
auto.delta = TRUE -
auto.cov.y = TRUE -
auto.cov.rv = FALSE, where lavaan knows the option: a random slope is not correlated with the other random effects of the between level, as in lavaan 0.7-3 and earlier
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
|
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 |
dp |
Default prior distributions for the different types of model
parameters; a named character vector as returned by |
test |
Character vector naming the post-estimation quantities to
compute and store with the fit. The atoms are |
vb_correction |
The variational Bayes (VB) correction of the posterior
mean of the Laplace approximation. |
marginal_method |
How the marginal posterior of each parameter is
approximated. |
marginal_scan |
How the scan behind each skew-normal marginal is taken.
|
marginal_laplace_fallback |
Logical. Rescan with
|
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 |
cov_as_cor |
Logical. Residual and latent-disturbance covariance
parameters ( |
sn_fit_sample |
Logical. When |
control |
A list of tuning settings, made by |
verbose |
Logical. With |
silent |
Logical. Print nothing at all, and muffle the warnings and
messages raised during the fit? Default |
cores |
A positive whole number or |
ppp_method |
How the PPP of a two-level model scores the observed and
the replicate data against the saturated model. |
ppp_nsamp |
The number of posterior draws, each with one replicate data
set, that the PPP of a two-level model uses. Defaults to |
wiggle |
Equality constraints to relax into approximate ones, as in
blavaan. |
wiggle.sd |
The standard deviation of the normal priors that |
n_qmc |
|
vb_method |
|
marginal_correction |
|
samp_copula |
|
samp_norta |
|
sn_fit_ngrid |
|
sn_fit_logthresh |
|
sn_fit_temp |
|
debug |
|
add_priors |
|
optim_method |
|
numerical_grad |
|
hessian_method |
|
... |
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:
-
int.ov.free = TRUE -
int.lv.free = FALSE -
auto.fix.first = TRUE(unlessstd.lv = TRUE) -
auto.fix.single = TRUE -
auto.var = TRUE -
auto.cov.lv.x = TRUE -
auto.efa = TRUE -
auto.th = TRUE -
auto.delta = TRUE -
auto.cov.y = TRUE -
auto.cov.rv = FALSE, where lavaan knows the option: a random slope is not correlated with the other random effects of the between level, as in lavaan 0.7-3 and earlier
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. |
rescale |
Character string controlling how the Bayesian chi-square
is rescaled. |
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 |
samp_copula |
|
... |
Additional arguments passed to methods. |
x |
An object of class |
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:
indicesNamed list of numeric vectors (one per posterior sample) for each computed fit index.
detailsList with
chisq(per-sample deviance,NAfor a draw that could not be scored),df,pD,rescale, andnsamp.
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 |
fit.measures |
Character vector of additional fit-measure names to
include (e.g. |
loo |
Logical; if |
object |
An INLAvaan object (the |
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:
-
npar: Number of free parameters.
-
Marg.Loglik: Approximated marginal log-likelihood.
-
logBF: Natural-log Bayes factor relative to the best model.
-
DIC / pD: Deviance Information Criterion and effective number of parameters (when the fit computed the DIC, i.e.
testincluded"dic"during fitting; the default"standard"does).
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
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. |
... |
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
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. |
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"):
nparNumber of free parameters.
converged1 if the optimiser converged, 0 otherwise.
iterationsNumber 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_infL-infinity norm of the analytic gradient at the mode (max |grad|). Should be ~0 at convergence.
grad_inf_relRelative L-infinity norm of the analytic gradient (max |grad| / (|par| + 1e-6)).
grad_l2L2 (Euclidean) norm of the analytic gradient at the mode.
mode_shift_maxMaximum, across parameters, of the Newton step at the reported mode in posterior-SD units (max |
\Omegagrad| / 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_condCondition 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_corThe 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_applied1 if VB correction was applied, 0 otherwise.
vb_shift_maxMaximum, across parameters, of the absolute VB correction in posterior-SD units (max |
vb_shift_sigma|).vb_kld_globalKL 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_maxMaximum per-parameter KL divergence from the VB correction.
kld_meanMean per-parameter KL divergence.
nmad_maxMaximum normalised max-absolute-deviation across the scanned marginals.
nmad_meanMean NMAD across the scanned marginals.
unscanned_mass_maxMaximum, across parameters, of
unscanned_mass(see below). Before INLAvaan 0.4.0 it wasscan_end_mass_max.grad_gap_maxMaximum
grad_gap(see below). Should be ~0.vb_fallback1 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_maxMaximum
vb_step_sigma(see below).vb_lhat,vb_j0,vb_j1The 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_lhatis the size of the residual of the VB equation at the step over its size at the mode.vb_j0andvb_j1are the slope of the map along the step, at the mode and at the step. The check passes whenvb_lhatis below 1 and both slopes lie between -1 and 1, and a value that is not finite fails it.NAwithvb_correction = "full", and when the step was belowvb_tol(seeinlavaan_control()) in every parameter, which is too small to check.vb_solve1 if the check of the one-step VB correction failed, 0 if it passed,
NAif 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 asONESTEP+SOLVE.mean_gap_maxMaximum, across parameters, of |
mean_gap| (see below).ridge_bend_maxMaximum
ridge_bend(see below).n_heavy_tailsNumber of marginals with heavy tails, those whose
tailsisFALSE.nsampNumber of posterior samples drawn.
psi_npd_shareShare 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 nopsimatrix has a free covariance.theta_npd_shareThe same share for the residual covariance matrix of the observed variables (
theta).vb_mcse_max,vb_mcse_meanDeprecated, 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:
namesParameter name.
gradAnalytic gradient of the negative log-posterior at the mode. Should be ~0 at convergence.
grad_absAbsolute analytic gradient.
grad_relRelative analytic gradient |grad| / (|par| + 1e-6), with par the posterior mean on the internal scale.
mode_shift_sigmaNewton step at the reported mode in posterior-SD units. Should be ~0 at convergence.
kldKL divergence between the Laplace Gaussian marginal and its VB-shifted copy,
vb_shift_sigma^2 / 2.vb_shiftVB correction shift (on the internal scale).
vb_shift_sigmaVB shift in units of posterior SD.
nmadNormalised max-absolute-deviation of the skew-normal fit from the scanned posterior.
alphaShape 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_massMass 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), whereFis the fitted skew-normal distribution function and\hat\theta_jthe 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 gives2\Phi(-4)= 6.3e-05, and healthy fits sit between 1e-03 and 1e-02. Before INLAvaan 0.4.0 it wasscan_end_mass.grad_gapHow 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_sigmaThe step still to go at the VB mean, in posterior-SD units, as
mode_shift_sigmais for the mode.NAafter 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: atvb_tol, atvb_maxitor at the cap on its cost thatvb_budgetsets (seeinlavaan_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. Withvb_budget = 0the 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_gapGap 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.
gamma1The volume correction of the scan: the slope, per posterior SD, added to the scanned log-posterior for the changing volume of the other parameters.
tailsFALSEwhen the density at an end of the scan is still above 5\ skew-normal extrapolates it.ridge_bendThe 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_sigmaDeprecated, and always
NA:grad_gapchecks the analytic gradient in place ofgrad_numandgrad_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:
the optimiser did not converge;
any parameter with
grad_gapabove 0.1;-
mode_shift_maxabove 0.1 posterior SDs; the VB correction did not converge:
vb_step_maxabove 0.1 posterior SDs, except after the solve that follows a failed one-step check;the one-step VB correction failed its check (
vb_solveis 1): the posterior is far from Gaussian along the mean correction. The warning names the parameter that the one step moved furthest, and when the solve that followed stopped withvb_step_maxabove 0.1 posterior SDs, it says so;any marginal with
nmadabove 0.1;any marginal with
unscanned_massabove 0.05;any marginal with heavy tails. When one of them is a loading of a factor that a marker identifies, the warning suggests
std.lv = TRUE, because a marker that loads weakly gives the other loadings of its factor such tails;any marginal with
ridge_bendabove 1, in a fit with another scan thanmarginal_scan = "laplace". The warning suggests that scan, which follows the ridge and takes longer;-
vb_shift_maxabove 1 posterior SD; -
hess_cond_corabove 1e8. The warning suggests checking that the model is identified, or more informative priors; the latent or residual covariance matrix is not positive definite at the posterior estimates (the check that lavaan runs after a fit);
-
psi_npd_shareortheta_npd_shareabove 0.01.
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"):
the data do not identify the model: the expected (Fisher) information at the posterior mode, which does not depend on the prior, has a condition number above 1e10 on the correlation scale. The warning names the parameters that move along the flattest direction. This check runs on single-level fits without random slopes or
conditional.x, and not withwiggle, whose priors identify the model on purpose;a variance is at zero (a Heywood case): the posterior median of a free variance is below 0.5\ variable at the mode. The posterior is valid; the warning suggests an informative prior where the analyst believes the value is. This check does not run on fits with random slopes;
the effective number of parameters
p_Dof the DIC is negative, so the DIC is not reliable for the fit.
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. |
logC |
Log-constant added to the log density, so that the density is
multiplied by |
log |
Logical; if |
lower_tail |
Logical; if |
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 |
threshold_log_drop |
A single finite negative number (default -6).
Points with |
temp |
A single finite positive number, the temperature of the weights
(default 1). |
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:
-
xi: location parameter -
omega: scale parameter -
alpha: shape parameter -
logC: log-constant, so thatexp(y)is approximated bydsnorm(x, xi, omega, alpha, logC) -
nmad: the largest absolute difference betweenexp(y)and the fitted density over all points, divided bymax(exp(y))
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 |
baseline_model |
The baseline (null) model for the incremental fit
indices (BCFI, BTLI, BNFI). |
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:
|
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. |
labels |
Logical. Attach variable names to the output. Default
|
... |
Currently unused. |
per_cluster |
Logical. For a random-slope model, return the moments
of each cluster instead of their average. Default |
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
|
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 first rows are those of the free parameters, with the names and in the order of
coef(). Each is the marginal of the parameter on the internal scale of the fit, on which a variance is a log variance, for example. The functionginvof the same parameter inpartablemaps the internal value to the parameter. It is increasing, so a quantile of the parameter isginvof the quantile of its row. For a covariance,ginvgives the correlation. For an intercept that the fit centres (seecentringininlavaan_control()and the elementcentred), the row is the marginal of its centred coordinate, the implied mean of its variable, soginvof its quantile is not a quantile of the intercept. A row withalphaequal to 0 is a normal marginal.The rows after them are marginals fitted to the posterior draws, on the scale that
summary()reports: the covariances (withcov_as_cor = FALSE), the centred intercepts and the parameters defined with:=. A covariance or a centred intercept then has two rows of the same name, and the second is its own. Withsn_fit_sample = FALSEthere are no such rows.With
marginal_method = "gaussian"there is no table (NULL). The marginal of a free parameter on the internal scale is then normal, with its mean intheta_starand its variance on the diagonal ofOmega. For a centred intercept, this is again the marginal of its centred coordinate, and its own draws are insummary_draws.
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
|
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 |
model.type |
The lavaan entry point used to fit |
dp |
Default prior distributions for the different types of model
parameters; a named character vector as returned by |
test |
Character vector naming the post-estimation quantities to
compute and store with the fit. The atoms are |
vb_correction |
The variational Bayes (VB) correction of the posterior
mean of the Laplace approximation. |
marginal_method |
How the marginal posterior of each parameter is
approximated. |
marginal_scan |
How the scan behind each skew-normal marginal is taken.
|
marginal_laplace_fallback |
Logical. Rescan with
|
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 |
cov_as_cor |
Logical. Residual and latent-disturbance covariance
parameters ( |
sn_fit_sample |
Logical. When |
control |
A list of tuning settings, made by |
verbose |
Logical. With |
silent |
Logical. Print nothing at all, and muffle the warnings and
messages raised during the fit? Default |
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 |
cores |
A positive whole number or |
ppp_method |
How the PPP of a two-level model scores the observed and
the replicate data against the saturated model. |
ppp_nsamp |
The number of posterior draws, each with one replicate data
set, that the PPP of a two-level model uses. Defaults to |
wiggle |
Equality constraints to relax into approximate ones, as in
blavaan. |
wiggle.sd |
The standard deviation of the normal priors that |
n_qmc |
|
vb_method |
|
marginal_correction |
|
samp_copula |
|
samp_norta |
|
sn_fit_ngrid |
|
sn_fit_logthresh |
|
sn_fit_temp |
|
debug |
|
add_priors |
|
optim_method |
|
numerical_grad |
|
hessian_method |
|
... |
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
|
mode_tol |
The relative tolerance of the search for the posterior mode
(the |
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_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 |
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 |
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 |
nlminb |
A named list of other controls of |
hessian |
How the Hessian at the posterior mode is differenced from the
analytic gradient. |
debug |
Logical. With |
add_priors |
Logical. With |
centring |
Logical. With |
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
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. |
... |
Currently unused. |
k |
Numeric penalty per parameter passed to the (disabled) |
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 |
... |
Not used, beyond catching the deprecated argument name
|
type |
Unit type: |
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 |
theta, Omega |
Optional posterior mean vector and covariance matrix
(in the unconstrained parameter space, as stored in |
cores |
Number of cores for the Hessian stage. The default |
verbose |
Logical; print progress (default |
object |
A fitted INLAvaan object, or an |
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_unitData frame of pointwise results, one row per unit:
unitCase number for LOSO, cluster position for LOCO.
groupGroup membership (multigroup fits only).
nobs1 for LOSO, the cluster size for LOCO.
l_starUnit log-likelihood at the summary.
score_normNorm of the unit score
s_u.lpd_1,lpd_2Pointwise log predictive density, at first and second order.
log_cpo_1,log_cpo_2Pointwise 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_sumLeverage diagnostics (see Details).
k_ssq\mathrm{tr}[(\Omega H_u)^2], consumed by the closed-formwaic()penalty.okWhether the second-order
\log \mathrm{CPO}exists.t_deltaComposite fits only: the drop in
\ell_uwhen the fixed indicator (co)variances are recomputed without the unit, already subtracted from the log CPO terms.
estimatesMatrix with rows
elpd_loo,p_loo,looicand columnsEstimate,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
NAwhen any\log \mathrm{CPO}_u^{(2)}does not exist. elpd_gap,pd_traceThe two sides of the curvature check (see Details); both are
NAat first order and partial totals under aunitssubset.type,flavour,n_units,n_groups,n_ok,n_lpd_ok,second_order,use_second,theta_overriddenMetadata.
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 |
... |
For an INLAvaan fit: |
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 |
params |
Character vector of parameter names to plot, as in
|
nrow, ncol |
Integer. Number of rows/columns for the facet grid when
|
use_ggplot |
Logical. When |
points |
Logical. When |
... |
Additional arguments (currently unused). |
See Also
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:
|
newdata |
An optional data frame of new observations. If supplied,
predictions are computed for |
level |
Integer; for |
nsamp |
Integer; number of posterior samples to use for prediction.
Defaults to |
ymis_only |
Logical; only applies when |
summary |
Logical. When |
... |
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:
-
nu = "normal(0,32)": Observed variable intercepts -
alpha = "normal(0,10)": Latent variable intercepts -
lambda = "normal(0,10)": Factor loadings -
beta = "normal(0,10)": Regression coefficients -
wmat = "normal(0,10)": Composite weights (<~) -
theta = "gamma(1,.5)[sd]": Residual variances (prior on the standard deviation) -
psi = "gamma(1,.5)[sd]": Latent variable variances (prior on the standard deviation) -
rho = "beta(1,1)": Correlations (both latent and observed) -
tau = "normal(0,1.5)": Thresholds for ordinal variables, which this version does not fit (see the section "Ordinal and binary data" ofinlavaan())
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:
-
[var]: Prior is on the variance\sigma^2. Example:"gamma(1,0.5)[var]"places a Gamma(1, 0.5) prior on the variance. A prior with no qualifier is also on the variance. -
[sd]: Prior is on the standard deviation\sigma. Example:"gamma(1,0.5)[sd]"places a Gamma(1, 0.5) prior on\sigma = \sqrt{\text{variance}}. -
[prec]: Prior is on the precision\tau = 1/\sigma^2. Example:"gamma(1,1)[prec]"places a Gamma(1, 1) prior on\tau = 1/\text{variance}. This corresponds to an Inverse-Gamma prior on the variance.
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. |
labels |
Logical. Attach variable names to the output. Default
|
... |
Currently unused. |
per_cluster |
Logical. For a random-slope model, return the residuals
of each cluster instead of the averaged ones. Default |
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 |
... |
Additional arguments (currently unused). |
type |
Character string specifying what to sample:
|
nsamp |
Number of samples to draw. |
samp_copula |
|
prior |
Logical. When |
silent |
Logical. When |
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 |
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 |
samp_copula |
|
silent |
Logical. When |
... |
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:
Draw
\boldsymbol\theta^{(s)}from the posterior (or prior).Compute the model-implied covariance
\boldsymbol\Sigma(\boldsymbol\theta^{(s)}). If it is not positive-definite, reject and redraw.Generate a dataset of
sample.nobsrows fromN(\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:
-
"truth"— named numeric vector of lavaan-side (x-space, constrained) parameter values used to generate the dataset. -
"truth_theta"— named numeric vector of the corresponding unconstrained (theta-space) parameter values. An intercept that the fit centres appears in its centred coordinate (seecentringininlavaan_control()), in the coordinates of this fit. A refit to a replicate can have other coordinates, because its covariates have other means. So for these intercepts, compare the refit with"truth"and its lavaan-side draws, not with"truth_theta"and its theta draws.
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:
|
se |
Logical. If TRUE, standard errors for the standardized parameters will be computed, together with a z-statistic and a p-value. |
ci |
If |
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 |
remove.eq |
Logical. If |
remove.ineq |
Logical. If |
remove.def |
Logical. If |
nsamp |
The number of samples to draw from the approximate posterior distribution for the calculation of standardised estimates. |
... |
Additional arguments sent to |
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
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
|
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
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
|
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 |
... |
Further arguments passed to |
evaluate |
Logical. If |
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
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. |
... |
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 |
... |
Not used. |
type |
Unit type: |
units |
Optional integer vector of unit indices to score; defaults to all units. |
second_order |
Logical; include the second-order (Hessian) terms
(default |
cores |
Number of cores for differentiating the unit scores. The
default |
verbose |
Logical; print progress (default |
object |
A fitted INLAvaan object, or an |
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
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)