| Title: | 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 (2026a) <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 (2026b) <doi:10.48550/arXiv.2604.00671>. |
| Authors: | Haziq Jamil [aut, cre, cph] (ORCID: <https://orcid.org/0000-0003-3298-1010>), Håvard Rue [ctb] (ORCID: <https://orcid.org/0000-0002-0222-1881>, Statistical and computational methodology), Alvin Bong [ctb] (Initial site build) |
| Maintainer: | Haziq Jamil <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.2.4.9001 |
| Built: | 2026-06-01 09:30:59 UTC |
| Source: | https://github.com/haziqj/inlavaan |
Fit an Approximate Bayesian Confirmatory Factor Analysis Model
acfa( model, data, dp = priors_for(), test = "standard", vb_correction = TRUE, marginal_method = c("skewnorm", "asymgaus", "marggaus", "sampling"), marginal_correction = c("shortcut", "shortcut_fd", "hessian", "none"), nsamp = 1000, samp_copula = TRUE, sn_fit_ngrid = 21, sn_fit_logthresh = -6, sn_fit_temp = 1, sn_fit_sample = TRUE, control = list(), verbose = TRUE, debug = FALSE, add_priors = TRUE, optim_method = c("nlminb", "ucminf", "optim"), numerical_grad = FALSE, use_gcp = FALSE, cores = NULL, ... )acfa( model, data, dp = priors_for(), test = "standard", vb_correction = TRUE, marginal_method = c("skewnorm", "asymgaus", "marggaus", "sampling"), marginal_correction = c("shortcut", "shortcut_fd", "hessian", "none"), nsamp = 1000, samp_copula = TRUE, sn_fit_ngrid = 21, sn_fit_logthresh = -6, sn_fit_temp = 1, sn_fit_sample = TRUE, control = list(), verbose = TRUE, debug = FALSE, add_priors = TRUE, optim_method = c("nlminb", "ucminf", "optim"), numerical_grad = FALSE, use_gcp = FALSE, cores = NULL, ... )
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. If some variables are declared as ordered factors, lavaan will treat them as ordinal variables. |
dp |
Default prior distributions on different types of
parameters, typically the result of a call to |
test |
Character indicating whether to compute posterior fit indices. Defaults to "standard". Change to "none" to skip these computations. |
vb_correction |
Logical indicating whether to apply a variational Bayes
correction for the posterior mean vector of estimates. Defaults to |
marginal_method |
The method for approximating the marginal posterior
distributions. Options include |
marginal_correction |
Which type of correction to use when fitting the
skew-normal or two-piece Gaussian marginals. |
nsamp |
The number of samples to draw for all sampling-based approaches (including posterior sampling for model fit indices). |
samp_copula |
Logical. When |
sn_fit_ngrid |
Number of grid points to lay out per dimension when
fitting the skew-normal marginals. A finer grid gives a better fit at the
cost of more joint-log-posterior evaluations. Defaults to |
sn_fit_logthresh |
The log-threshold for fitting the skew-normal. Points
with log-posterior drop below this threshold (relative to the maximum) will
be excluded from the fit. Defaults to |
sn_fit_temp |
Temperature parameter for fitting the skew-normal.
Defaults to |
sn_fit_sample |
Logical. When |
control |
A list of control parameters for the optimiser. |
verbose |
Logical indicating whether to print progress messages. |
debug |
Logical indicating whether to return debug information. |
add_priors |
Logical indicating whether to include prior densities in the posterior computation. |
optim_method |
The optimisation method to use for finding the posterior
mode. Options include |
numerical_grad |
Logical indicating whether to use numerical gradients
for the optimisation. Defaults to |
use_gcp |
EXPIRMENTAL!!! Logical indicating whether to use the GCP parametrisation for covariance. |
cores |
Integer or |
... |
Additional arguments to be passed to the lavaan::lavaan model fitting function. |
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 (unless std.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
For further information regarding these arguments, please refer to the
lavaan::lavOptions() documentation.
An S4 object of class INLAvaan which is a subclass of the
lavaan::lavaan class.
Typically, users will interact with the specific latent variable
model functions instead, including acfa(), asem(), and agrowth().
# 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)# 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
agrowth( model, data, dp = priors_for(), test = "standard", vb_correction = TRUE, marginal_method = c("skewnorm", "asymgaus", "marggaus", "sampling"), marginal_correction = c("shortcut", "shortcut_fd", "hessian", "none"), nsamp = 1000, samp_copula = TRUE, sn_fit_ngrid = 21, sn_fit_logthresh = -6, sn_fit_temp = 1, sn_fit_sample = TRUE, control = list(), verbose = TRUE, debug = FALSE, add_priors = TRUE, optim_method = c("nlminb", "ucminf", "optim"), numerical_grad = FALSE, use_gcp = FALSE, cores = NULL, ... )agrowth( model, data, dp = priors_for(), test = "standard", vb_correction = TRUE, marginal_method = c("skewnorm", "asymgaus", "marggaus", "sampling"), marginal_correction = c("shortcut", "shortcut_fd", "hessian", "none"), nsamp = 1000, samp_copula = TRUE, sn_fit_ngrid = 21, sn_fit_logthresh = -6, sn_fit_temp = 1, sn_fit_sample = TRUE, control = list(), verbose = TRUE, debug = FALSE, add_priors = TRUE, optim_method = c("nlminb", "ucminf", "optim"), numerical_grad = FALSE, use_gcp = FALSE, cores = NULL, ... )
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. If some variables are declared as ordered factors, lavaan will treat them as ordinal variables. |
dp |
Default prior distributions on different types of
parameters, typically the result of a call to |
test |
Character indicating whether to compute posterior fit indices. Defaults to "standard". Change to "none" to skip these computations. |
vb_correction |
Logical indicating whether to apply a variational Bayes
correction for the posterior mean vector of estimates. Defaults to |
marginal_method |
The method for approximating the marginal posterior
distributions. Options include |
marginal_correction |
Which type of correction to use when fitting the
skew-normal or two-piece Gaussian marginals. |
nsamp |
The number of samples to draw for all sampling-based approaches (including posterior sampling for model fit indices). |
samp_copula |
Logical. When |
sn_fit_ngrid |
Number of grid points to lay out per dimension when
fitting the skew-normal marginals. A finer grid gives a better fit at the
cost of more joint-log-posterior evaluations. Defaults to |
sn_fit_logthresh |
The log-threshold for fitting the skew-normal. Points
with log-posterior drop below this threshold (relative to the maximum) will
be excluded from the fit. Defaults to |
sn_fit_temp |
Temperature parameter for fitting the skew-normal.
Defaults to |
sn_fit_sample |
Logical. When |
control |
A list of control parameters for the optimiser. |
verbose |
Logical indicating whether to print progress messages. |
debug |
Logical indicating whether to return debug information. |
add_priors |
Logical indicating whether to include prior densities in the posterior computation. |
optim_method |
The optimisation method to use for finding the posterior
mode. Options include |
numerical_grad |
Logical indicating whether to use numerical gradients
for the optimisation. Defaults to |
use_gcp |
EXPIRMENTAL!!! Logical indicating whether to use the GCP parametrisation for covariance. |
cores |
Integer or |
... |
Additional arguments to be passed to the lavaan::lavaan model fitting function. |
The asem() 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 (unless std.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
An S4 object of class INLAvaan which is a subclass of the
lavaan::lavaan class.
Typically, users will interact with the specific latent variable
model functions instead, including acfa(), asem(), and agrowth().
# 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)# 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
as_fun_string(f)as_fun_string(f)
f |
Function to convert. |
A single character vector representing the function.
f <- function(x) { x^2 + 1 } as_fun_string(f)f <- function(x) { x^2 + 1 } as_fun_string(f)
Fit an Approximate Bayesian Structural Equation Model
asem( model, data, dp = priors_for(), test = "standard", vb_correction = TRUE, marginal_method = c("skewnorm", "asymgaus", "marggaus", "sampling"), marginal_correction = c("shortcut", "shortcut_fd", "hessian", "none"), nsamp = 1000, samp_copula = TRUE, sn_fit_ngrid = 21, sn_fit_logthresh = -6, sn_fit_temp = 1, sn_fit_sample = TRUE, control = list(), verbose = TRUE, debug = FALSE, add_priors = TRUE, optim_method = c("nlminb", "ucminf", "optim"), numerical_grad = FALSE, use_gcp = FALSE, cores = NULL, ... )asem( model, data, dp = priors_for(), test = "standard", vb_correction = TRUE, marginal_method = c("skewnorm", "asymgaus", "marggaus", "sampling"), marginal_correction = c("shortcut", "shortcut_fd", "hessian", "none"), nsamp = 1000, samp_copula = TRUE, sn_fit_ngrid = 21, sn_fit_logthresh = -6, sn_fit_temp = 1, sn_fit_sample = TRUE, control = list(), verbose = TRUE, debug = FALSE, add_priors = TRUE, optim_method = c("nlminb", "ucminf", "optim"), numerical_grad = FALSE, use_gcp = FALSE, cores = NULL, ... )
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. If some variables are declared as ordered factors, lavaan will treat them as ordinal variables. |
dp |
Default prior distributions on different types of
parameters, typically the result of a call to |
test |
Character indicating whether to compute posterior fit indices. Defaults to "standard". Change to "none" to skip these computations. |
vb_correction |
Logical indicating whether to apply a variational Bayes
correction for the posterior mean vector of estimates. Defaults to |
marginal_method |
The method for approximating the marginal posterior
distributions. Options include |
marginal_correction |
Which type of correction to use when fitting the
skew-normal or two-piece Gaussian marginals. |
nsamp |
The number of samples to draw for all sampling-based approaches (including posterior sampling for model fit indices). |
samp_copula |
Logical. When |
sn_fit_ngrid |
Number of grid points to lay out per dimension when
fitting the skew-normal marginals. A finer grid gives a better fit at the
cost of more joint-log-posterior evaluations. Defaults to |
sn_fit_logthresh |
The log-threshold for fitting the skew-normal. Points
with log-posterior drop below this threshold (relative to the maximum) will
be excluded from the fit. Defaults to |
sn_fit_temp |
Temperature parameter for fitting the skew-normal.
Defaults to |
sn_fit_sample |
Logical. When |
control |
A list of control parameters for the optimiser. |
verbose |
Logical indicating whether to print progress messages. |
debug |
Logical indicating whether to return debug information. |
add_priors |
Logical indicating whether to include prior densities in the posterior computation. |
optim_method |
The optimisation method to use for finding the posterior
mode. Options include |
numerical_grad |
Logical indicating whether to use numerical gradients
for the optimisation. Defaults to |
use_gcp |
EXPIRMENTAL!!! Logical indicating whether to use the GCP parametrisation for covariance. |
cores |
Integer or |
... |
Additional arguments to be passed to the lavaan::lavaan model fitting function. |
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 (unless std.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
For further information regarding these arguments, please refer to the
lavaan::lavOptions() documentation.
An S4 object of class INLAvaan which is a subclass of the
lavaan::lavaan class.
Typically, users will interact with the specific latent variable
model functions instead, including acfa(), asem(), and agrowth().
# 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)# 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)
Compute posterior distributions of Bayesian fit indices for an INLAvaan
model, analogous to blavaan::blavFitIndices().
bfit_indices( object, baseline.model = NULL, rescale = c("devM", "MCMC"), nsamp = NULL, samp_copula = TRUE ) ## S3 method for class 'bfit_indices' summary(object, ...) ## S3 method for class 'bfit_indices' print(x, ...)bfit_indices( object, baseline.model = NULL, rescale = c("devM", "MCMC"), nsamp = NULL, samp_copula = TRUE ) ## S3 method for class 'bfit_indices' summary(object, ...) ## S3 method for class 'bfit_indices' print(x, ...)
object |
An object of class INLAvaan. |
baseline.model |
An optional INLAvaan object representing the baseline (null) model. Required for incremental fit indices (BCFI, BTLI, BNFI). |
rescale |
Character string controlling how the Bayesian chi-square
is rescaled. |
nsamp |
Number of posterior samples to draw. Defaults to the value used when fitting the model. |
samp_copula |
Logical. When |
... |
Additional arguments passed to methods. |
x |
An object of class |
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), df, pD,
rescale, and nsamp.
Use summary() to obtain a table of posterior summaries (Mean, SD,
quantiles, Mode) for each index.
lavaan::fitMeasures(), blavaan::blavFitIndices(),
fitmeasures(), compare()
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, verbose = FALSE) # Absolute fit indices bf <- bfit_indices(fit) bf summary(bf)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, verbose = FALSE) # Absolute fit indices bf <- bfit_indices(fit) bf summary(bf)
Compare two or more Bayesian SEM fitted with INLAvaan, reporting model-fit statistics and (optionally) fit indices side by side.
compare(x, y, ..., fit.measures = NULL) ## S4 method for signature 'INLAvaan' compare(x, y, ..., fit.measures = NULL)compare(x, y, ..., fit.measures = NULL) ## S4 method for signature 'INLAvaan' compare(x, y, ..., fit.measures = NULL)
x |
An INLAvaan (or |
y, ...
|
One or more INLAvaan (or |
fit.measures |
Character vector of additional fit-measure names to
include (e.g. |
The first argument x serves as the baseline (null) model.
All models (including the baseline) appear in the comparison table. The
baseline is also passed to fitMeasures() when
incremental fit indices (BCFI, BTLI, BNFI) are requested via
fit.measures.
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 test != "none" was used during fitting).
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.
A data frame of class compare.inlavaan_internal containing model
fit statistics, sorted by descending marginal log-likelihood.
https://lavaan.ugent.be/tutorial/groups.html
# 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"))# 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
dbeta_box(x, shape1, shape2, a, b, log = FALSE)dbeta_box(x, shape1, shape2, a, b, log = FALSE)
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). |
A numeric vector of density values.
# 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)")# 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)")
Extract convergence and approximation-quality diagnostics from a fitted
INLAvaan model.
diagnostics(object, ...) ## S4 method for signature 'INLAvaan' diagnostics(object, type = c("global", "param"), ...)diagnostics(object, ...) ## S4 method for signature 'INLAvaan' diagnostics(object, type = c("global", "param"), ...)
object |
An object of class INLAvaan. |
... |
Currently unused. |
type |
Character. |
Global diagnostics (type = "global"):
nparNumber of free parameters.
nsampNumber of posterior samples drawn.
converged1 if the optimiser converged, 0 otherwise.
iterationsNumber of optimiser iterations.
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.
hess_condCondition number of the Hessian (precision matrix)
computed from . Large values indicate near-singularity.
vb_kld_globalGlobal KL divergence from the VB mean correction (NA if VB correction was not applied).
vb_applied1 if VB correction was applied, 0 otherwise.
kld_maxMaximum per-parameter KL divergence from the VB correction.
kld_meanMean per-parameter KL divergence.
nmad_maxMaximum normalised max-absolute-deviation across marginals (skew-normal method only; NA otherwise).
nmad_meanMean NMAD across marginals.
Per-parameter diagnostics (type = "param"):
A data frame with columns:
paramParameter name.
gradAnalytic gradient of the negative log-posterior at the mode. Should be ~0 at convergence.
grad_numNumerical (finite-difference) gradient at the mode.
Should agree with grad; large discrepancies indicate a bug in the
analytic gradient.
grad_diffDifference grad_num - grad: should be ~0.
grad_absAbsolute analytic gradient.
grad_relRelative analytic gradient |grad| / (|par| + 1e-6).
kldPer-parameter KL divergence from the VB correction.
vb_shiftVB correction shift (in original scale).
vb_shift_sigmaVB shift in units of posterior SD.
nmadNormalised max-absolute-deviation of the skew-normal fit (NA when not using the skewnorm method).
For type = "global", a named numeric vector (class
"diagnostics.INLAvaan"). For type = "param", a data frame
(class c("diagnostics.INLAvaan.param", "data.frame")).
timing(), fitmeasures(), plot()
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", verbose = FALSE) # Global convergence summary diagnostics(fit) # Per-parameter table diagnostics(fit, type = "param")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", verbose = FALSE) # Global convergence summary diagnostics(fit) # Per-parameter table diagnostics(fit, type = "param")
Density for the skew normal distribution with location xi, scale omega,
and shape alpha.
dsnorm(x, xi, omega, alpha, logC = 0, log = FALSE)dsnorm(x, xi, omega, alpha, logC = 0, log = FALSE)
x |
Vector of quantiles. |
xi |
Location parameter. |
omega |
Scale parameter. |
alpha |
Shape parameter. |
logC |
Log-normalization constant. |
log |
Logical; if TRUE, returns the log density. |
A numeric vector of (log) density values.
https://en.wikipedia.org/wiki/Skew_normal_distribution
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")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")
Fit a skew normal distribution to log-density evaluations
fit_skew_normal(x, y, threshold_log_drop = -6, temp = NA)fit_skew_normal(x, y, threshold_log_drop = -6, temp = NA)
x |
A numeric vector of points where the density is evaluated. |
y |
A numeric vector of log-density evaluations at points x. |
threshold_log_drop |
A negative numeric value indicating the log-density drop threshold below which points are ignored in the fitting. Default is -6. |
temp |
A numeric value for the temperature parameter k. If NA (default), it is included in the optimisation. |
This skew normal fitting function uses a weighted least squares
approach to fit the log-density evaluations provided in y at points x.
The weights are set to be the density evaluations raised to the power of
the temperature parameter k. This has somewhat an interpretation of
finding the skew normal fit that minimises the Kullback-Leibler divergence
from the true density to it.
In R-INLA, the C code implementation from which this was translated from can be found here.
A list with fitted parameters:
xi: location parameter
omega: scale parameter
alpha: shape parameter
logC: log-normalization constant
k: temperature parameter
rsq: R-squared of the fit
Note that logC and k are not used when fitting from a sample.
# 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 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
fit_skew_normal_samp(x)fit_skew_normal_samp(x)
x |
A numeric vector of sample data. |
Uses maximum likelihood estimation to fit a skew normal distribution
to the provided numeric vector x.
A list with fitted parameters:
xi: location parameter
omega: scale parameter
alpha: shape parameter
logC: log-normalization constant
k: temperature parameter
rsq: R-squared of the fit
Note that logC and k are not used when fitting from a sample.
x <- rnorm(100, mean = 5, sd = 1) unlist(fit_skew_normal_samp(x))x <- rnorm(100, mean = 5, sd = 1) unlist(fit_skew_normal_samp(x))
Fit Measures for a Latent Variable Model estimated using INLA
## S4 method for signature 'INLAvaan' fitMeasures( object, fit.measures = "all", baseline.model = NULL, h1.model = NULL, fm.args = list(standard.test = "default", scaled.test = "default", rmsea.ci.level = 0.9, rmsea.close.h0 = 0.05, rmsea.notclose.h0 = 0.08, robust = TRUE, cat.check.pd = TRUE), output = "vector", ... ) ## S4 method for signature 'INLAvaan' fitmeasures( object, fit.measures = "all", baseline.model = NULL, h1.model = NULL, fm.args = list(standard.test = "default", scaled.test = "default", rmsea.ci.level = 0.9, rmsea.close.h0 = 0.05, rmsea.notclose.h0 = 0.08, robust = TRUE, cat.check.pd = TRUE), output = "vector", ... )## S4 method for signature 'INLAvaan' fitMeasures( object, fit.measures = "all", baseline.model = NULL, h1.model = NULL, fm.args = list(standard.test = "default", scaled.test = "default", rmsea.ci.level = 0.9, rmsea.close.h0 = 0.05, rmsea.notclose.h0 = 0.08, robust = TRUE, cat.check.pd = TRUE), output = "vector", ... ) ## S4 method for signature 'INLAvaan' fitmeasures( object, fit.measures = "all", baseline.model = NULL, h1.model = NULL, fm.args = list(standard.test = "default", scaled.test = "default", rmsea.ci.level = 0.9, rmsea.close.h0 = 0.05, rmsea.notclose.h0 = 0.08, robust = TRUE, cat.check.pd = TRUE), output = "vector", ... )
object |
An object of class INLAvaan. |
fit.measures |
If |
baseline.model |
An optional INLAvaan object representing the
baseline (null) model. Required for incremental fit indices (BCFI, BTLI,
BNFI). Must have been fitted with |
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). |
... |
Additional arguments. Currently supports:
|
A named numeric vector of fit measures.
bfit_indices(), compare(), diagnostics()
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, verbose = FALSE) # All available fit measures fitMeasures(fit) # Specific measures fitMeasures(fit, c("npar", "DIC", "pD", "ppp"))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, verbose = FALSE) # All available fit measures fitMeasures(fit) # Specific measures fitMeasures(fit, c("npar", "DIC", "pD", "ppp"))
Returns the inlavaan_internal list stored inside a fitted INLAvaan
object, optionally extracting a single named element.
get_inlavaan_internal(object, what)get_inlavaan_internal(object, what)
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
|
The full inlavaan_internal list, or the named element when
what is supplied.
INLAvaan, diagnostics(), timing()
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", verbose = FALSE) # Full internal object int <- get_inlavaan_internal(fit) names(int) # Extract a specific element get_inlavaan_internal(fit, "coefficients")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", verbose = FALSE) # Full internal object int <- get_inlavaan_internal(fit) names(int) # Extract a specific element get_inlavaan_internal(fit, "coefficients")
This function fits a Bayesian latent variable model by approximating the posterior distributions of the model parameters using various methods, including skew-normal, asymmetric Gaussian, marginal Gaussian, or sampling-based approaches. It leverages the lavaan package for model specification and estimation.
inlavaan( model, data, model.type = "sem", dp = priors_for(), test = "standard", vb_correction = TRUE, marginal_method = c("skewnorm", "asymgaus", "marggaus", "sampling"), marginal_correction = c("shortcut", "shortcut_fd", "hessian", "none"), nsamp = 1000, samp_copula = TRUE, sn_fit_ngrid = 21, sn_fit_logthresh = -6, sn_fit_temp = 1, sn_fit_sample = TRUE, control = list(), verbose = TRUE, debug = FALSE, add_priors = TRUE, optim_method = c("nlminb", "ucminf", "optim"), numerical_grad = FALSE, use_gcp = FALSE, cores = NULL, ... )inlavaan( model, data, model.type = "sem", dp = priors_for(), test = "standard", vb_correction = TRUE, marginal_method = c("skewnorm", "asymgaus", "marggaus", "sampling"), marginal_correction = c("shortcut", "shortcut_fd", "hessian", "none"), nsamp = 1000, samp_copula = TRUE, sn_fit_ngrid = 21, sn_fit_logthresh = -6, sn_fit_temp = 1, sn_fit_sample = TRUE, control = list(), verbose = TRUE, debug = FALSE, add_priors = TRUE, optim_method = c("nlminb", "ucminf", "optim"), numerical_grad = FALSE, use_gcp = FALSE, cores = NULL, ... )
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. If some variables are declared as ordered factors, lavaan will treat them as ordinal variables. |
model.type |
Set the model type: possible values
are |
dp |
Default prior distributions on different types of
parameters, typically the result of a call to |
test |
Character indicating whether to compute posterior fit indices. Defaults to "standard". Change to "none" to skip these computations. |
vb_correction |
Logical indicating whether to apply a variational Bayes
correction for the posterior mean vector of estimates. Defaults to |
marginal_method |
The method for approximating the marginal posterior
distributions. Options include |
marginal_correction |
Which type of correction to use when fitting the
skew-normal or two-piece Gaussian marginals. |
nsamp |
The number of samples to draw for all sampling-based approaches (including posterior sampling for model fit indices). |
samp_copula |
Logical. When |
sn_fit_ngrid |
Number of grid points to lay out per dimension when
fitting the skew-normal marginals. A finer grid gives a better fit at the
cost of more joint-log-posterior evaluations. Defaults to |
sn_fit_logthresh |
The log-threshold for fitting the skew-normal. Points
with log-posterior drop below this threshold (relative to the maximum) will
be excluded from the fit. Defaults to |
sn_fit_temp |
Temperature parameter for fitting the skew-normal.
Defaults to |
sn_fit_sample |
Logical. When |
control |
A list of control parameters for the optimiser. |
verbose |
Logical indicating whether to print progress messages. |
debug |
Logical indicating whether to return debug information. |
add_priors |
Logical indicating whether to include prior densities in the posterior computation. |
optim_method |
The optimisation method to use for finding the posterior
mode. Options include |
numerical_grad |
Logical indicating whether to use numerical gradients
for the optimisation. Defaults to |
use_gcp |
EXPIRMENTAL!!! Logical indicating whether to use the GCP parametrisation for covariance. |
cores |
Integer or |
... |
Additional arguments to be passed to the lavaan::lavaan model fitting function. |
An S4 object of class INLAvaan which is a subclass of the
lavaan::lavaan class.
Typically, users will interact with the specific latent variable
model functions instead, including acfa(), asem(), and agrowth().
# 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)# 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)
This is a class that extends the lavaan::lavaan class. Several S4 methods are available.
## 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, standardized = FALSE, rsquare = FALSE, postmedian = FALSE, postmode = FALSE, nmad = TRUE, kld = FALSE, vb_shift = FALSE, priors = TRUE, nd = 3L, ... )## 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, standardized = FALSE, rsquare = FALSE, postmedian = FALSE, postmode = FALSE, nmad = TRUE, kld = FALSE, vb_shift = FALSE, priors = TRUE, nd = 3L, ... )
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 PPP). |
estimates |
Logical; if TRUE, print parameter estimates table. |
standardized |
Logical; if TRUE, include standardized estimates. |
rsquare |
Logical; if TRUE, include R-square values. |
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; number of decimal places to print for numeric values. |
externalA list containing an inlavaan_internal object.
lavaan::lavaan, inlavaan(), acfa(), asem(), agrowth()
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", verbose = FALSE) # Print basic info fit # Detailed summary summary(fit) # Extract coefficients coef(fit)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", verbose = FALSE) # Print basic info fit # Detailed summary summary(fit) # Extract coefficients coef(fit)
Helper function to check if two functions are the same
is_same_function(f, g)is_same_function(f, g)
f, g
|
Functions to compare. |
Logical.
f1 <- function(x) { x^2 + 1 } f2 <- function(x) { x^2 + 1 } is_same_function(f1, f2) # TRUEf1 <- function(x) { x^2 + 1 } f2 <- function(x) { x^2 + 1 } is_same_function(f1, f2) # TRUE
Generates diagnostic plots for a fitted INLAvaan model.
## 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, ... )## 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, ... )
x |
An object of class INLAvaan. |
y |
Not used. |
type |
Character. One of |
params |
Character vector of parameter names to plot, or |
nrow, ncol
|
Integer. Number of rows/columns for the facet grid when
|
use_ggplot |
Logical. When |
points |
Logical. When |
... |
Additional arguments (currently unused). |
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", verbose = FALSE) # Posterior marginal densities (default) plot(fit) # Skew-normal fit diagnostic for a single parameter plot(fit, type = "sn_fit", params = "visual=~x1")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", verbose = FALSE) # Posterior marginal densities (default) plot(fit) # Skew-normal fit diagnostic for a single parameter plot(fit, type = "sn_fit", params = "visual=~x1")
Compute posterior predictions from a fitted INLAvaan model,
including latent variable scores, predicted observed values, and imputed
missing data.
## 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, ... )## 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, ... )
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 |
... |
Currently unused. |
A matrix of posterior draws with rows corresponding to samples and
columns to variables or latent factors, or a list of such matrices when
ymis_only = FALSE.
sampling(), simulate(), summary()
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", verbose = FALSE) # Posterior latent variable scores lv_scores <- predict(fit) head(lv_scores) # Predicted observed variable means yhat <- predict(fit, type = "yhat") head(yhat)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", verbose = FALSE) # Posterior latent variable scores lv_scores <- predict(fit) head(lv_scores) # Predicted observed variable means yhat <- predict(fit, type = "yhat") head(yhat)
Specify priors for a SEM, similar to how blavaan::dpriors() works.
priors_for(...)priors_for(...)
... |
Named arguments specifying prior distributions for lavaan parameter types. |
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
theta = "gamma(1,.5)[sd]": Residual precisions
psi = "gamma(1,.5)[sd]": Latent variable precisions
rho = "beta(1,1)": Correlations (both latent and observed)
tau = "normal(0,1.5)": Thresholds for ordinal variables
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).
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.).
For variance parameters (theta, psi), the prior distribution
can be placed on a transformed scale by appending a qualifier:
[sd]: Prior is on the standard deviation .
Example: "gamma(1,0.5)[sd]" places a Gamma(1, 0.5) prior on
.
[prec]: Prior is on the precision .
Example: "gamma(1,1)[prec]" places a Gamma(1, 1) prior on
. This is the parameterisation used by
blavaan and corresponds to an Inverse-Gamma prior on the variance.
The necessary Jacobian adjustment is applied automatically in both cases.
inlavaan(), acfa(), asem(), agrowth()
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]")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]")
A fast approximation of skew-normal quantiles using the high-performance approximation algorithm from the INLA GMRFLib C source, and originally by Thomas Luu (see details for reference).
qsnorm_fast(p, xi = 0, omega = 1, alpha = 0)qsnorm_fast(p, xi = 0, omega = 1, alpha = 0)
p |
Vector of probabilities. |
xi |
Location parameter (numeric vector). |
omega |
Scale parameter (numeric vector). |
alpha |
Shape parameter (numeric vector). |
This function implements a high-performance approximation for the
skew-normal quantile function based on the algorithm described by Luu
(2016). The method uses a domain decomposition strategy to achieve high
accuracy ( relative error) without iterative numerical
inversion.
The domain is split into two regions:
Tail Regions: For extreme probabilities where is large, the quantile
is approximated using the Lambert W-function, , solving via
asymptotic expansion:
Central Region: For the main body of the distribution, the function uses a high-order Taylor expansion of the inverse error function around a carefully selected expansion point $x_0$:
This approach is significantly faster than standard numerical inversion
(e.g., uniroot) while maintaining sufficient precision for most
statistical applications.
Vector of quantiles.
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/
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)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)
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).
sampling(object, ...) ## S4 method for signature 'INLAvaan' sampling( object, type = c("lavaan", "theta", "latent", "observed", "implied", "all"), nsamp = 1000L, samp_copula = TRUE, prior = FALSE, silent = FALSE, ... )sampling(object, ...) ## S4 method for signature 'INLAvaan' sampling( object, type = c("lavaan", "theta", "latent", "observed", "implied", "all"), nsamp = 1000L, samp_copula = TRUE, prior = FALSE, silent = FALSE, ... )
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 |
Logical. When |
prior |
Logical. When |
silent |
Logical. When |
Each row of the output corresponds to a fresh parameter draw: a new
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:
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
conditional on observed data.
A matrix or named list, depending on type.
simulate() for generating complete replicate datasets (e.g.,
for SBC); predict() for individual-specific factor scores;
bfit_indices() for Bayesian fit indices.
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) # Compare copula vs Gaussian sampling s_cop <- sampling(fit, nsamp = 500, samp_copula = TRUE) s_gaus <- sampling(fit, nsamp = 500, samp_copula = FALSE) # Prior predictive samples y_prior <- sampling(fit, type = "observed", nsamp = 500, prior = TRUE)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) # Compare copula vs Gaussian sampling s_cop <- sampling(fit, nsamp = 500, samp_copula = TRUE) s_gaus <- sampling(fit, nsamp = 500, samp_copula = FALSE) # Prior predictive samples y_prior <- sampling(fit, type = "observed", nsamp = 500, prior = TRUE)
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.
## S4 method for signature 'INLAvaan' simulate( object, nsim = 1L, seed = NULL, sample.nobs = NULL, prior = FALSE, samp_copula = TRUE, silent = FALSE, ... )## S4 method for signature 'INLAvaan' simulate( object, nsim = 1L, seed = NULL, sample.nobs = NULL, prior = FALSE, samp_copula = TRUE, silent = FALSE, ... )
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. Defaults to the sample size of the original data. |
prior |
Logical. When |
samp_copula |
Logical. When |
silent |
Logical. When |
... |
Additional arguments (currently unused). |
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 :
Draw from the posterior (or prior).
Compute the model-implied covariance
.
If it is not positive-definite, reject and redraw.
Generate a dataset of sample.nobs rows from
.
Parameter draws reuse the same internal machinery as sampling()
(sample_params_prior / sample_params_posterior), so the prior
specification is consistent.
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.
sampling() for single-observation draws from the predictive
distribution (prior/posterior predictive checks).
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)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
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, ... )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, ... )
object |
An object of class INLAvaan. |
type |
If |
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 TRUE, the (residual) observed covariances are scaled by the square root of the ‘Theta’ diagonal elements, and the (residual) latent covariances are scaled by the square root of the ‘Psi’ diagonal elements. If FALSE, the (residual) observed covariances are scaled by the square root of the diagonal elements of the observed model-implied covariance matrix (Sigma), and the (residual) latent covariances are scaled by the square root of diagonal elements of the model-implied covariance matrix of the latent variables. |
remove.eq |
Logical. If TRUE, filter the output by removing all rows containing equality constraints, if any. |
remove.ineq |
Logical. If TRUE, filter the output by removing all rows containing inequality constraints, if any. |
remove.def |
Logical. If TRUE, filter the ouitput by removing all rows containing parameter definitions, if any. |
nsamp |
The number of samples to draw from the approximate posterior distribution for the calculation of standardised estimates. |
... |
Additional arguments sent to |
A data.frame containing standardised model parameters.
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 = FALSE, verbose = FALSE ) standardisedsolution(fit, nsamp = 10, se = FALSE, ci = FALSE)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 = FALSE, verbose = FALSE ) standardisedsolution(fit, nsamp = 10, se = FALSE, ci = FALSE)
Extract wall-clock timings for individual computation stages of a fitted
INLAvaan model.
timing(object, ...) ## S4 method for signature 'INLAvaan' timing(object, what = "total", ...)timing(object, ...) ## S4 method for signature 'INLAvaan' timing(object, what = "total", ...)
object |
An object of class INLAvaan. |
... |
Currently unused. |
what |
Character vector of timing segment names to return, or
|
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.
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", verbose = FALSE) # Total elapsed time timing(fit) # All stages timing(fit, what = "all") # Specific stages timing(fit, what = c("optim", "marginals"))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", verbose = FALSE) # Total elapsed time timing(fit) # All stages timing(fit, what = "all") # Specific stages timing(fit, what = c("optim", "marginals"))
Extract the posterior variance-covariance matrix of model parameters from a
fitted INLAvaan model.
## S4 method for signature 'INLAvaan' vcov(object, type = c("lavaan", "theta"), ...)## S4 method for signature 'INLAvaan' vcov(object, type = c("lavaan", "theta"), ...)
object |
An object of class INLAvaan. |
type |
Character. |
... |
Currently unused. |
A square numeric matrix.
summary(), coef(), standardisedsolution()
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", verbose = FALSE) # Default: posterior covariance of lavaan parameters vcov(fit) # Internal parameterisation (Laplace approximation) vcov(fit, type = "theta")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", verbose = FALSE) # Default: posterior covariance of lavaan parameters vcov(fit) # Internal parameterisation (Laplace approximation) vcov(fit, type = "theta")