| Title: | Bayesian Estimation of Dynamic VAR Models using STAN |
|---|---|
| Description: | Bayesian estimation of multilevel Vector Autoregression (VAR) models using Stan. Supports Gaussian, Binary, and Ordinal (adjacent category) outcome variables with random effects and customizable priors. |
| Authors: | Florian Metwaly [aut, cre, cph] (ORCID: <https://orcid.org/0009-0001-8357-7870>) |
| Maintainer: | Florian Metwaly <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 1.0.0 |
| Built: | 2026-05-27 14:44:22 UTC |
| Source: | https://github.com/cran/bvarnet |
Computes Savage-Dickey density ratio Bayes factors for each (requested set of) parameter in the model.
By default, all applicable parameters are tested and returned in a tidy data frame.
The type argument controls which parameter groups are included; the variable argument can be used to filter to effects involving specific variables.
The log_BF10 argument allows including the natural log of the Bayes factor in the output, and round controls numeric rounding of the results.
bf_table( object, type = "all", lag = 1L, null_value = 0, variable = NULL, log_BF10 = FALSE, round = 5L )bf_table( object, type = "all", lag = 1L, null_value = 0, variable = NULL, log_BF10 = FALSE, round = 5L )
object |
A |
type |
Character vector specifying which parameter groups to test.
Use
|
lag |
Integer; which lag block to use (default 1). Applies to
|
null_value |
Numeric scalar; the null hypothesis value (default 0). |
variable |
Character vector or |
log_BF10 |
Logical; if |
round |
Integer or |
A data frame with columns: type, predictor,
outcome, BF10 (and optionally log_BF10).
The bvar function estimates the posterior distribution of the specified Bayesian (Multilevel) Vector Autoregression.
bvar( id_col, time_col, y_cols, x_cols = NULL, center_x = FALSE, fe_interactions = NULL, re_interactions = NULL, re_cols = NULL, re_temporal = FALSE, K = 1, na_action = c("listwise"), skip_lag = TRUE, data, family = c("bernoulli", "ordinal", "gaussian"), priors = set_priors(), iter = 4000, warmup = 1000, chains = 4, cores = 1, seed = NULL, adapt_delta = NULL, max_treedepth = NULL, save_data = FALSE )bvar( id_col, time_col, y_cols, x_cols = NULL, center_x = FALSE, fe_interactions = NULL, re_interactions = NULL, re_cols = NULL, re_temporal = FALSE, K = 1, na_action = c("listwise"), skip_lag = TRUE, data, family = c("bernoulli", "ordinal", "gaussian"), priors = set_priors(), iter = 4000, warmup = 1000, chains = 4, cores = 1, seed = NULL, adapt_delta = NULL, max_treedepth = NULL, save_data = FALSE )
id_col |
Character. Name of the subject/group identifier column. |
time_col |
Character. Name of the time column. |
y_cols |
Character vector. Names of the outcome columns. |
x_cols |
Character vector or NULL. Names of the covariate columns. |
center_x |
Logical. Grand-mean centre covariates before fitting?
Default |
fe_interactions |
List or NULL. Fixed-effect interaction terms to add
to the design matrix. Each element is a character vector of column names
to interact, or |
re_interactions |
List or NULL. Random-effect interaction terms. |
re_cols |
Character vector. Columns from X and/or "Intercept" to include as random slopes. |
re_temporal |
Logical. Include random slopes on lag predictors?
Default |
K |
Integer. AR order. Default 1. |
na_action |
Character. Missing-data strategy; currently only
|
skip_lag |
Logical. If |
data |
Data frame in long format. |
family |
Character scalar or vector. Observation model per node.
A scalar is recycled to all |
priors |
A |
iter |
Integer. Number of post-warmup iterations per chain. Default 4000. |
warmup |
Integer. Number of warmup iterations per chain. Default 1000. |
chains |
Integer. Number of MCMC chains. Default 4. |
cores |
Integer. Number of chains to run in parallel. Default 1. |
seed |
Integer or NULL. RNG seed. |
adapt_delta |
Numeric in (0, 1). Target average proposal acceptance
probability during warmup adaptation. Higher values (e.g., 0.95–0.99)
reduce divergences at the cost of slower sampling. Default |
max_treedepth |
Integer. Maximum depth of the NUTS binary tree.
Increasing this allows the sampler to take more leapfrog steps per
iteration, which can help with difficult posteriors (e.g., funnels in
hierarchical logistic models) but increases computation. Default
|
save_data |
Logical. If |
A bvarnet object (a named list) with slots:
draws, convergence, diagnostics, timing,
metadata, return_codes, family, standata,
priors. If save_data = TRUE, also includes
data_used (the cleaned estimation data frame).
## Not run: # Run bvar on studentlife data data(studentlife, package = "bvarnet") fit <- bvar( id_col = "id", time_col = "time", y_cols = c("anxious", "calm", "conventional", "critical", "dependable"), re_temporal = TRUE, K = 1, data = studentlife, family = "ordinal", priors = set_priors(), seed = 1337) summary(fit) ## End(Not run)## Not run: # Run bvar on studentlife data data(studentlife, package = "bvarnet") fit <- bvar( id_col = "id", time_col = "time", y_cols = c("anxious", "calm", "conventional", "critical", "dependable"), re_temporal = TRUE, K = 1, data = studentlife, family = "ordinal", priors = set_priors(), seed = 1337) summary(fit) ## End(Not run)
Extracts posterior summaries from a fitted bvarnet object and
compares them to the true parameter values used for data generation.
compare_to_truth( fit, truth, ci_width = 0.9, bayes_factor = FALSE, null_value = 0 )compare_to_truth( fit, truth, ci_width = 0.9, bayes_factor = FALSE, null_value = 0 )
fit |
A fitted |
truth |
The |
ci_width |
Numeric. Width of the credible interval (default 0.90). |
bayes_factor |
Logical; if |
null_value |
Numeric scalar; the null hypothesis value for Bayes
factor computation (default 0). Only used when |
A data frame with columns: parameter, node, true_value, post_mean, post_sd, ci_lower, ci_upper, covered (logical), and optionally BF01, BF10, bf_correct.
Returns an (iterations * chains) by params matrix with
Stan-indexed column names (e.g. "beta[1,1]", "phi[2,3]").
extract_draws(object, parameter = c("beta", "phi", "sd_u", "sigma", "kappa"))extract_draws(object, parameter = c("beta", "phi", "sd_u", "sigma", "kappa"))
object |
A |
parameter |
Character. One of |
A numeric matrix with one row per posterior draw and one column per Stan parameter element.
Returns a named p x p matrix of posterior summary statistics for
the VAR lag coefficients at a chosen lag, suitable for network
visualisation (e.g., with igraph or qgraph).
extract_network_matrix( object, lag = 1L, stat = c("mean", "median", "q5", "q95") )extract_network_matrix( object, lag = 1L, stat = c("mean", "median", "q5", "q95") )
object |
A |
lag |
Integer. Which lag block. Default 1. |
stat |
Character. Summary statistic to fill the matrix with:
|
A named p x p numeric matrix. Element [i, j]
gives the effect of variable i (lagged) on variable j
(outcome). Row and column names are the outcome variable names.
Returns a single flat data frame with posterior summaries (mean, median, 5th/95th percentiles) and convergence diagnostics (Rhat, ESS) for all model parameters.
extract_param(object, bayes_factor = FALSE, null_value = 0, type = NULL)extract_param(object, bayes_factor = FALSE, null_value = 0, type = NULL)
object |
A |
bayes_factor |
Logical; if |
null_value |
Numeric scalar; the null hypothesis value for Bayes
factor computation (default 0). Only used when |
type |
Character vector or |
A data frame with columns: type, predictor,
outcome, mean, median, q5, q95,
rhat, ess_bulk, ess_tail, and optionally
BF01, BF10.
Returns random-effect standard deviations (group-level variance),
subject-level posterior means, or the full posterior draws of the
subject-level random effects u.
extract_random_effects(object, what = c("sd", "mean_u", "draws_u"))extract_random_effects(object, what = c("sd", "mean_u", "draws_u"))
object |
A |
what |
Character. What to extract:
|
Depends on what; see above.
Returns a data frame of autoregressive and/or cross-lagged parameter summaries with convergence diagnostics, filtered by lag and effect type.
extract_temporal( object, lag = NULL, effect = c("all", "ar", "cl"), bayes_factor = FALSE, null_value = 0 )extract_temporal( object, lag = NULL, effect = c("all", "ar", "cl"), bayes_factor = FALSE, null_value = 0 )
object |
A |
lag |
Integer or |
effect |
Character. One of |
bayes_factor |
Logical; if |
null_value |
Numeric; null hypothesis for BF. Default 0. |
A data frame with columns type, predictor,
outcome, mean, median, q5, q95,
rhat, ess_bulk, ess_tail, and optionally
BF01, BF10.
Format a bvarnet_prior for printing
## S3 method for class 'bvarnet_prior' format(x, half = FALSE, ...)## S3 method for class 'bvarnet_prior' format(x, half = FALSE, ...)
x |
A |
half |
Logical; if |
... |
Ignored. |
A character string.
Returns a bvarnet_priors object showing the default priors that
apply to a particular model configuration. Parameters irrelevant to
the chosen family or model structure are omitted, so the returned object
reflects what the sampler will actually use.
get_default_priors(family = NULL, has_re = TRUE)get_default_priors(family = NULL, has_re = TRUE)
family |
Character (optional). One of |
has_re |
Logical. Does the model include random effects?
Default |
A bvarnet_priors object.
Displays a brief summary of the fitted model: family, dimensions, Rhat, divergences, chain return codes, priors, and total sampling time.
## S3 method for class 'bvarnet' print(x, ...)## S3 method for class 'bvarnet' print(x, ...)
x |
A |
... |
Ignored. |
x invisibly.
Print a bvarnet_prior
## S3 method for class 'bvarnet_prior' print(x, ...)## S3 method for class 'bvarnet_prior' print(x, ...)
x |
A |
... |
Passed to |
x invisibly.
Shows only the priors explicitly set by the user. When no priors have been overridden (all defaults), a compact note is printed instead.
## S3 method for class 'bvarnet_priors' print(x, ...)## S3 method for class 'bvarnet_priors' print(x, ...)
x |
A |
... |
Ignored. |
x invisibly.
Pretty-prints the output of summary.bvarnet, grouping
parameters by type and displaying convergence information.
Each group is truncated to max_rows rows; use extract_param()
or dedicated extractors to see full output.
## S3 method for class 'summary.bvarnet' print(x, digits = 3, max_rows = 10, ...)## S3 method for class 'summary.bvarnet' print(x, digits = 3, max_rows = 10, ...)
x |
A |
digits |
Number of decimal digits for numeric columns. Default 3. |
max_rows |
Maximum number of rows to print per parameter group. Default 10. |
... |
Ignored. |
x invisibly.
Builds a bvarnet_prior object specifying the prior family and its
parameters. Supported families in Phase 1 are "normal",
"student_t", and "cauchy".
prior(family, loc = 0, scale = 1, df = 7)prior(family, loc = 0, scale = 1, df = 7)
family |
Character. One of |
loc |
Location parameter (default 0). |
scale |
Scale parameter (default 1). Must be > 0. |
df |
Degrees of freedom for |
A bvarnet_prior S3 object.
bvar()
Returns a bvarnet_priors object containing a bvarnet_prior
for every model parameter type. Any argument left as NULL uses the
package default.
Available prior distributions are:
normal(loc, scale)
student_t(loc, scale, df)
cauchy(loc, scale)
For standart deviations and random effects, the prior is automatically converted to a half-prior (truncated at loc) in the Stan code, so the printed format reflects this.
set_priors( intercept = NULL, beta = NULL, phi = NULL, sd_u = NULL, kappa = NULL, sigma = NULL )set_priors( intercept = NULL, beta = NULL, phi = NULL, sd_u = NULL, kappa = NULL, sigma = NULL )
intercept |
Prior for the intercept. Only applies to gaussian and bernoulli models; for ordinal models the intercept is absorbed into the kappa (threshold parameter). |
beta |
Prior for fixed-effect regression coefficients (slopes). |
phi |
Prior for lag coefficients. |
sd_u |
Prior for random-effect standard deviations (half-prior). |
kappa |
Prior for ordinal cut-points (ordinal models only). |
sigma |
Prior for residual standard deviation (gaussian models only; half-prior). |
A bvarnet_priors S3 object.
Generates data from the generative model implied by each Stan model family. Useful for testing parameter recovery and model validation.
sim_var( N, T_obs, p, K = 1L, family = c("bernoulli", "ordinal", "gaussian"), alpha = NULL, gamma = NULL, Phi = NULL, sigma = NULL, kappa = NULL, q = 0L, x_gen = NULL, sd_alpha = 0.5, sd_phi = 0.2, sd_gamma = NULL, re_temporal = FALSE, C = 5L, burnin = 500L, seed = NULL )sim_var( N, T_obs, p, K = 1L, family = c("bernoulli", "ordinal", "gaussian"), alpha = NULL, gamma = NULL, Phi = NULL, sigma = NULL, kappa = NULL, q = 0L, x_gen = NULL, sd_alpha = 0.5, sd_phi = 0.2, sd_gamma = NULL, re_temporal = FALSE, C = 5L, burnin = 500L, seed = NULL )
N |
Integer. Number of subjects (groups). |
T_obs |
Integer. Number of time points per subject. |
p |
Integer. Number of outcome nodes. |
K |
Integer. AR order (default 1). |
family |
Character. One of |
alpha |
Numeric vector of length |
gamma |
Matrix |
Phi |
Matrix |
sigma |
Numeric vector of length |
kappa |
List of |
q |
Integer. Number of covariates (default 0). |
x_gen |
Function |
sd_alpha |
Numeric. SD of random intercepts (scalar or p-vector). Default 0.5. Set to 0 to simulate a fixed-effects-only model with no between-person variation in intercepts. |
sd_phi |
Numeric. SD of random lag coefficients (scalar or matrix). Default 0.2. |
sd_gamma |
Numeric or NULL. SD of random covariate slopes. NULL means no random slopes on covariates. |
re_temporal |
Logical. Include random slopes on lag predictors? Default FALSE. |
C |
Integer. Number of ordinal categories (ordinal only, default 5). |
burnin |
Integer. Number of time points to discard as warmup before
recording data (default 500). The VAR process is simulated for
|
seed |
Integer or NULL. RNG seed. |
To simulate a VAR without any random effects (i.e. all subjects share
identical parameters), set sd_alpha = 0, re_temporal = FALSE
(the default), and sd_gamma = NULL (the default).
A list with two components:
A long-format data frame with columns id, t,
y_1, ..., y_p, and optionally x_1, ..., x_q.
A list of true generating parameters.
Assessing mental health, academic performance and behavioral trends of college students using smartphones. Wang, R., Chen, F., Chen, Z., Li, T., Harari, G., Tignor, S., Zhou, X., Ben-Zeev, D., & Campbell, A. T. (2014). StudentLife: assessing mental health, academic performance and behavioral trends of college students using smartphones. Proceedings of the 2014 ACM International Joint Conference on Pervasive and Ubiquitous Computing, 3–14. https://doi.org/10.1145/2632048.2632054
studentlifestudentlife
studentlifeA data frame with 1912 rows and 72 columns:
https://openesmdata.org/datasets/0004_wang/
https://doi.org/10.1145/2632048.2632054
Returns a labelled posterior summary table grouped by parameter type,
with convergence diagnostics and optional Bayes factors. Wraps
extract_param.
## S3 method for class 'bvarnet' summary(object, bayes_factor = FALSE, null_value = 0, ...)## S3 method for class 'bvarnet' summary(object, bayes_factor = FALSE, null_value = 0, ...)
object |
A |
bayes_factor |
Logical; if |
null_value |
Numeric scalar; null hypothesis value for BF computation. Default 0. |
... |
Ignored. |
An object of class "summary.bvarnet" (a list) with elements:
Data frame from extract_param().
Model family.
Number of outcome variables.
AR order.
Number of observations.
Maximum Rhat across all parameters.
Total divergent transitions.