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

View source: R/dbn.R

run_dbnR Documentation

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, dir_csv = NULL, dir_out = NULL, dir_figs = NULL)

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.

dir_csv

Character scalar or NULL; directory where the preprocessed data ("dbn_data.csv") is written. If NULL (default), no CSV is written.

dir_out

Character scalar or NULL; directory where the fitted objects ("dbn_fit.rds") are saved. If NULL (default), nothing is saved to disk.

dir_figs

Character scalar or NULL; directory where the DAG plot ("dbn_graph.png") is written, if Rgraphviz is available. If NULL (default), no figure is produced.

Details

This function requires the bnlearn package (listed under Suggests); an informative error is raised at call time if it is not installed. 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 and dir_figs is supplied, a graph of the learned DAG is produced and saved as "dbn_graph.png" in that directory. When dir_csv is supplied, the preprocessed data used to fit the DBN are written to "dbn_data.csv"; when dir_out is supplied, the fitted objects are saved as "dbn_fit.rds".

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.

Examples


# This example runs only when 'bnlearn' is installed.
if (requireNamespace("bnlearn", quietly = TRUE)) {
  DT <- data.frame(
    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))
  )

  dbn_res <- run_dbn(DT)
  print(dbn_res$dag)
}



bivarhr documentation built on July 7, 2026, 1:06 a.m.