The dcvar package uses rstan as its default backend for Bayesian model fitting.
# Install rstan (available on CRAN)
install.packages("rstan")
# Install dcvar from GitHub
install.packages("remotes")
remotes::install_github("benlug/dcvar")Optionally, you can use cmdstanr as an alternative backend by installing it and CmdStan:
dcvar includes trajectory generators and a data simulator for testing:
library(dcvar)
# Generate a decreasing rho trajectory (therapy effect)
rho_true <- rho_decreasing(n_time = 150, rho_start = 0.7, rho_end = 0.3)
# Simulate bivariate VAR(1) data with this trajectory
sim <- simulate_dcvar(
n_time = 150,
rho_trajectory = rho_true,
seed = 42
)
head(sim$Y_df)
#> time y1 y2
#> 1 1 0.0000000 0.0000000
#> 2 2 1.3709584 0.5378943
#> 3 3 0.8282054 1.0071266
#> 4 4 0.7534426 0.5867669
#> 5 5 1.7962315 1.2239371
#> 6 6 2.6796869 1.8905391The main fitting function is dcvar(). It accepts a data
frame and the names of two variables to model:
# Quick overview
print(fit)
# Detailed summary
summary(fit)
# Posterior means for VAR parameters
coef(fit)
# Time-varying rho as a data frame
rho_df <- rho_trajectory(fit)
head(rho_df)
# MCMC diagnostics
dcvar_diagnostics(fit)The fitted() method returns one-step-ahead fitted values
from the VAR(1) component. The predict() method adds
marginal prediction intervals for normal margin fits:
Use as.data.frame() to export the full parameter summary
as a tidy data frame:
# Rho trajectory with credible intervals
# Red line = true trajectory (simulation only)
plot_rho(fit, true_rho = sim$true_params$rho)
# VAR coefficient heatmap
plot_phi(fit)
# MCMC diagnostics (trace, Rhat, ESS)
plot(fit, type = "diagnostics")
# Posterior predictive check
# Currently available for normal and exponential margins
plot_ppc(fit)