| Title: | Bayesian Estimation of Dynamic VAR Models using STAN |
| Version: | 1.0.0 |
| Author: | Florian Metwaly |
| Maintainer: | Florian Metwaly <f.j.metwaly@uva.nl> |
| 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. |
| License: | GPL (≥ 3) |
| Encoding: | UTF-8 |
| URL: | https://flo1met.github.io/bvarnet/, https://github.com/flo1met/bvarnet |
| BugReports: | https://github.com/flo1met/bvarnet/issues |
| RoxygenNote: | 7.3.3 |
| Additional_repositories: | https://mc-stan.org/r-packages/ |
| Imports: | instantiate, logspline, mvtnorm, posterior |
| Suggests: | cmdstanr, bayesplot, knitr, qgraph, rmarkdown, testthat (≥ 3.0.0) |
| Config/testthat/edition: | 3 |
| Config/Needs/website: | pkgdown |
| VignetteBuilder: | knitr |
| Depends: | R (≥ 3.5) |
| LazyData: | true |
| NeedsCompilation: | yes |
| Packaged: | 2026-05-19 10:29:47 UTC; florianmetwaly |
| Repository: | CRAN |
| Date/Publication: | 2026-05-27 09:00:02 UTC |
bvarnet: 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.
Author(s)
Maintainer: Florian Metwaly f.j.metwaly@uva.nl (ORCID) [copyright holder]
See Also
Useful links:
Report bugs at https://github.com/flo1met/bvarnet/issues
Compute Savege-Dickey Bayes factors
Description
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.
Usage
bf_table(
object,
type = "all",
lag = 1L,
null_value = 0,
variable = NULL,
log_BF10 = FALSE,
round = 5L
)
Arguments
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 |
Value
A data frame with columns: type, predictor,
outcome, BF10 (and optionally log_BF10).
Fit a Bayesian multilevel VAR network model
Description
The bvar function estimates the posterior distribution of the specified Bayesian (Multilevel) Vector Autoregression.
Usage
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
)
Arguments
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 |
Value
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).
Examples
## 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)
Compare fitted model parameters to simulation truth
Description
Extracts posterior summaries from a fitted bvarnet object and
compares them to the true parameter values used for data generation.
Usage
compare_to_truth(
fit,
truth,
ci_width = 0.9,
bayes_factor = FALSE,
null_value = 0
)
Arguments
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 |
Value
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.
Extract raw posterior draws for a single parameter block
Description
Returns an (iterations * chains) by params matrix with
Stan-indexed column names (e.g. "beta[1,1]", "phi[2,3]").
Usage
extract_draws(object, parameter = c("beta", "phi", "sd_u", "sigma", "kappa"))
Arguments
object |
A |
parameter |
Character. One of |
Value
A numeric matrix with one row per posterior draw and one column per Stan parameter element.
Extract a network matrix of temporal coefficients
Description
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).
Usage
extract_network_matrix(
object,
lag = 1L,
stat = c("mean", "median", "q5", "q95")
)
Arguments
object |
A |
lag |
Integer. Which lag block. Default 1. |
stat |
Character. Summary statistic to fill the matrix with:
|
Value
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.
Extract labelled parameter summaries from a fitted bvarnet model
Description
Returns a single flat data frame with posterior summaries (mean, median, 5th/95th percentiles) and convergence diagnostics (Rhat, ESS) for all model parameters.
Usage
extract_param(object, bayes_factor = FALSE, null_value = 0, type = NULL)
Arguments
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 |
Value
A data frame with columns: type, predictor,
outcome, mean, median, q5, q95,
rhat, ess_bulk, ess_tail, and optionally
BF01, BF10.
Extract random-effect summaries
Description
Returns random-effect standard deviations (group-level variance),
subject-level posterior means, or the full posterior draws of the
subject-level random effects u.
Usage
extract_random_effects(object, what = c("sd", "mean_u", "draws_u"))
Arguments
object |
A |
what |
Character. What to extract:
|
Value
Depends on what; see above.
Extract temporal (VAR lag) effects
Description
Returns a data frame of autoregressive and/or cross-lagged parameter summaries with convergence diagnostics, filtered by lag and effect type.
Usage
extract_temporal(
object,
lag = NULL,
effect = c("all", "ar", "cl"),
bayes_factor = FALSE,
null_value = 0
)
Arguments
object |
A |
lag |
Integer or |
effect |
Character. One of |
bayes_factor |
Logical; if |
null_value |
Numeric; null hypothesis for BF. Default 0. |
Value
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
Description
Format a bvarnet_prior for printing
Usage
## S3 method for class 'bvarnet_prior'
format(x, half = FALSE, ...)
Arguments
x |
A |
half |
Logical; if |
... |
Ignored. |
Value
A character string.
Get the default prior specification for a given model family
Description
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.
Usage
get_default_priors(family = NULL, has_re = TRUE)
Arguments
family |
Character (optional). One of |
has_re |
Logical. Does the model include random effects?
Default |
Value
A bvarnet_priors object.
Print a bvarnet model object
Description
Displays a brief summary of the fitted model: family, dimensions, Rhat, divergences, chain return codes, priors, and total sampling time.
Usage
## S3 method for class 'bvarnet'
print(x, ...)
Arguments
x |
A |
... |
Ignored. |
Value
x invisibly.
Print a bvarnet_prior
Description
Print a bvarnet_prior
Usage
## S3 method for class 'bvarnet_prior'
print(x, ...)
Arguments
x |
A |
... |
Passed to |
Value
x invisibly.
Print a bvarnet_priors specification
Description
Shows only the priors explicitly set by the user. When no priors have been overridden (all defaults), a compact note is printed instead.
Usage
## S3 method for class 'bvarnet_priors'
print(x, ...)
Arguments
x |
A |
... |
Ignored. |
Value
x invisibly.
Print a bvarnet summary
Description
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.
Usage
## S3 method for class 'summary.bvarnet'
print(x, digits = 3, max_rows = 10, ...)
Arguments
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. |
Value
x invisibly.
Construct a single prior distribution
Description
Builds a bvarnet_prior object specifying the prior family and its
parameters. Supported families in Phase 1 are "normal",
"student_t", and "cauchy".
Usage
prior(family, loc = 0, scale = 1, df = 7)
Arguments
family |
Character. One of |
loc |
Location parameter (default 0). |
scale |
Scale parameter (default 1). Must be > 0. |
df |
Degrees of freedom for |
Value
A bvarnet_prior S3 object.
Build a prior specification object for bvar()
Description
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.
Usage
set_priors(
intercept = NULL,
beta = NULL,
phi = NULL,
sd_u = NULL,
kappa = NULL,
sigma = NULL
)
Arguments
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). |
Value
A bvarnet_priors S3 object.
Simulate data from a multilevel VAR model
Description
Generates data from the generative model implied by each Stan model family. Useful for testing parameter recovery and model validation.
Usage
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
)
Arguments
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. |
Details
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).
Value
A list with two components:
- data
A long-format data frame with columns
id,t,y_1, ...,y_p, and optionallyx_1, ...,x_q.- truth
A list of true generating parameters.
StudentLife Data
Description
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
Usage
studentlife
Format
studentlife
A data frame with 1912 rows and 72 columns:
Source
https://openesmdata.org/datasets/0004_wang/
https://doi.org/10.1145/2632048.2632054
Summary method for bvarnet objects
Description
Returns a labelled posterior summary table grouped by parameter type,
with convergence diagnostics and optional Bayes factors. Wraps
extract_param.
Usage
## S3 method for class 'bvarnet'
summary(object, bayes_factor = FALSE, null_value = 0, ...)
Arguments
object |
A |
bayes_factor |
Logical; if |
null_value |
Numeric scalar; null hypothesis value for BF computation. Default 0. |
... |
Ignored. |
Value
An object of class "summary.bvarnet" (a list) with elements:
- table
Data frame from
extract_param().- family
Model family.
- p
Number of outcome variables.
- K
AR order.
- n
Number of observations.
- rhat_max
Maximum Rhat across all parameters.
- n_divergences
Total divergent transitions.