Learn R Programming

bivarhr (version 0.1.5)

run_dbn: Fit a Two-Slice Dynamic Bayesian Network (DBN) for I, C, and Regime

Description

Constructs and estimates a simple two-slice Dynamic Bayesian Network (DBN) over discretized versions of I, C, and Regime using bnlearn. The network includes current and lag-1 nodes for each variable, with structural constraints enforcing the DBN topology.

Usage

run_dbn(DT)

Value

A list with components:

  • dag: the learned Bayesian network structure (bnlearn "bn" object).

  • fit: the fitted DBN ("bn.fit" object).

  • data: the processed data frame (Ic, Cc, R, and their lag-1 versions) used to learn/fit the DBN.

Arguments

DT

A data.frame or data.table containing at least:

  • I_cat, C_cat: discretized (e.g., tercile) versions of I and C.

  • Regime: categorical regime indicator.

The function internally renames these to Ic, Cc, and R, constructs their lag-1 counterparts, and drops rows with missing lags.

Details

The DBN is defined on the nodes Ic, Cc, R, Ic_l1, Cc_l1, R_l1. A blacklist is used to forbid arrows from current to lagged nodes, while a whitelist ensures arrows from lagged to current nodes:

  • Blacklist: Ic → Ic_l1, Cc → Cc_l1, R → R_l1.

  • Whitelist: Ic_l1 → Ic, Cc_l1 → Cc, R_l1 → R.

The structure is learned via hill-climbing (bnlearn::hc()) with BDe score (score = "bde") and imaginary sample size iss = 10. Parameters are then estimated via bnlearn::bn.fit() using Bayesian estimation with the same iss.

If Rgraphviz is available, a graph of the learned DAG is produced and saved as "dbn_graph.png" in the directory specified by a global object dir_figs (character scalar). The preprocessed data used to fit the DBN are written to "dbn_data.csv" in dir_csv, and the fitted objects are saved as "dbn_fit.rds" in dir_out.

The function assumes that dir_csv, dir_out, and (optionally) dir_figs exist as global character scalars specifying output directories.

Examples

Run this code
# \donttest{
library(data.table)

# 1. Create dummy data (Fixed: wrapped in factor() for bnlearn)
DT <- data.table(
  I_cat  = factor(sample(c("Low", "Medium", "High"), 100, replace = TRUE)),
  C_cat  = factor(sample(c("Low", "Medium", "High"), 100, replace = TRUE)),
  Regime = factor(sample(c("Growth", "Crisis"), 100, replace = TRUE))
)

# 2. Define global paths using tempdir()
tmp_dir <- tempdir()
dir_csv  <- file.path(tmp_dir, "csv")
dir_out  <- file.path(tmp_dir, "dbn")
dir_figs <- file.path(tmp_dir, "figs")

dir.create(dir_csv,  showWarnings = FALSE, recursive = TRUE)
dir.create(dir_out,  showWarnings = FALSE, recursive = TRUE)
dir.create(dir_figs, showWarnings = FALSE, recursive = TRUE)

# 3. Run the function
dbn_res <- run_dbn(DT)

# Inspect the result
print(dbn_res$dag)
# }

Run the code above in your browser using DataLab