Last updated: 2021-04-14

Checks: 6 1

Knit directory: 2020_cts_bn/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


The R Markdown file has unstaged changes. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20200907) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 5ff7ce6. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/

Unstaged changes:
    Modified:   analysis/2-bn_analysis.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/2-bn_analysis.Rmd) and HTML (docs/2-bn_analysis.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 5ff7ce6 bernard-liew 2021-04-14 Added bnviewer
Rmd 880adc7 bernard-liew 2021-04-13 updated bn analysis
html c142098 bernard-liew 2020-11-23 Build site.
Rmd 2266d36 bernard-liew 2020-11-23 added explanation to graphs
html a6948ce bernard-liew 2020-10-26 initial analysis
Rmd fe17d91 bernard-liew 2020-10-26 initial analysis

Introduction

This is an example of a Bayesian network, with directed arcs. I only perform the analysis on a subset of provided variables.

Import libraries

rm (list = ls())
# Helper
library (tidyverse)

# BN
library (bnlearn)

# Model
library (caret)

# Feature parallel
library (doParallel)

# Plot
library (Rgraphviz)
library (bnviewer)

Import data

dat <- readRDS ("output/dat.RDS")

load ("output/bn_data.RData")

Collapse variables

dat <- dat %>%
  mutate (ppt_medn_base = (ppt_medn_aff_base + ppt_medn_naff_base)/2,
          ppt_uln_base = (ppt_uln_aff_base + ppt_uln_naff_base)/2,
          ppt_radn_base = (ppt_radn_aff_base + ppt_radn_naff_base)/2,
          ppt_neck_base = (ppt_neck_aff_base + ppt_neck_naff_base)/2,
          ppt_cts_base = (ppt_cts_aff_base + ppt_cts_naff_base)/2,
          ppt_ta_base = (ppt_ta_aff_base + ppt_ta_naff_base)/2) %>%
  select (-c(ppt_medn_aff_base:ppt_ta_naff_base)) 

BN analysis

Create blacklist

var.excl <- c(grep ("groc", names (dat), value = TRUE) ,
              grep ("mean", names (dat), value = TRUE),
              #grep ("base", names (dat), value = TRUE), 
              #"age", 
              #"pain_years", 
              #"pain_extent", 
              "aff_side" 
              #"emg"
              )
df.bn = as.data.frame (dat)[, !names (dat) %in% var.excl] %>%
  na.omit()

names (df.bn)[grepl ("years", names (df.bn))] <- "duration"
names (df.bn)[grepl ("extent", names (df.bn))] <- "area"
names (df.bn)[grepl ("cts_base", names (df.bn))] <- "ct_base"
names (df.bn)[grepl ("ppt", names (df.bn))] <- str_remove (names (df.bn)[grepl ("ppt", names (df.bn))], "ppt_")
names (df.bn)[grepl ("cts", names (df.bn))] <- str_remove (names (df.bn)[grepl ("cts", names (df.bn))], "cts_")
names (df.bn)[grepl ("worst", names (df.bn))] <- str_remove (names (df.bn)[grepl ("worst", names (df.bn))], "worst_")


df.bn$grp <- factor (df.bn$grp)

rx.var <- "grp"
demo.var = grep("age|duration|emg", colnames (df.bn), value = TRUE)
base.var = grep("_base", colnames (df.bn), value = TRUE)
mth1.var = grep("_1m", colnames (df.bn), value = TRUE)
mth3.var = grep("_3m", colnames (df.bn), value = TRUE)
mth6.var = grep("_6m", colnames (df.bn), value = TRUE)
outcome.var = grep("_12m", colnames (df.bn), value = TRUE)

pair_var <- expand.grid(from = names (df.bn),
                        to = names (df.bn)) %>%
  rownames_to_column()

tiers_keep <- pair_var %>%
  filter (!(grepl (paste0(outcome.var, collapse = "|"),from))) %>%
  filter (!(grepl (paste0(rx.var, collapse = "|"),to))) %>%
  filter (!(grepl (paste0(mth6.var, collapse = "|"), from) &
              grepl (paste0(c(demo.var, base.var, mth1.var, mth3.var), collapse = "|"),to))) %>%
  filter (!(grepl (paste0(mth3.var, collapse = "|"), from) &
              grepl (paste0(c(demo.var, base.var, mth1.var), collapse = "|"),to))) %>%
  filter (!(grepl (paste0(mth1.var, collapse = "|"), from) &
            grepl (paste0(c(demo.var, base.var), collapse = "|"),to))) %>%
  filter (!(grepl (paste0(base.var, collapse = "|"), from) &
          grepl (paste0(c(demo.var), collapse = "|"),to))) %>%
  filter (!(grepl (paste0(rx.var, collapse = "|"), from) &
          grepl (paste0(c(demo.var, base.var), collapse = "|"),to)))

bl <- anti_join(pair_var, tiers_keep, by = "rowname")  %>%
  filter (from != to) %>%
  select (from, to)

Build the final model using model averaging

set.seed (123)
boot <- boot.strength(df.bn,
                      R = 200,
                      algorithm = "hc",
                      algorithm.args = list (blacklist = bl))

Get averaged model

“Underneath” the model is a complex mathematical relationship between each variables.The figure is meant to illustrate a complex model simply. Interpretation of a Bayesian Network model should be natural, the arrows reflect the direction of relationship. Example, grp influences cts_func_12m partly by cts_func_1m and partly directly. The thickness of the arrows reflect how common one would expect to find such a relationship should many separate experiments be collected. Whether the arrows reflect causal relationships really depend if we think these variables represent an exhaustive list of plausible biological causes. In this case, I do not think we can say it is causal, but we can certainly understand a complex relationship driving recovery.

avg <-  averaged.network(boot, threshold = 0.5)
fit <-  bn.fit (avg, df.bn, method = "mle")
g <- strength.plot(avg, boot, shape = "ellipse", render = FALSE)
graph::nodeRenderInfo(g) = list(fontsize=18)
#Rgraphviz::renderGraph(g)
viewer(avg,
       bayesianNetwork.width = "100%",
       bayesianNetwork.height = "80vh",
       bayesianNetwork.layout = "layout_with_sugiyama",
       bayesianNetwork.title="Bayesian Network of CTS recovery",
       node.font = list(color = "black", face="Arial", size = 16),
       bayesianNetwork.footer = "Fig. 1 - Layout with Sugiyama"
)

Performance evaluation using nested cross validation.

Not run yet.

Inner is bootstrap resampling for model averaging. Outer is bootstrap resampling k = 25 for performance evaluation.

set.seed (1256)

flds <- createFolds(1:nrow(df.bn), 
                            k = 10, returnTrain = TRUE)
n_boot = 200
doParallel::registerDoParallel(7)

corr.df.list <- list()

for (k in seq_along(flds)) {
  
  train <-  df.bn [flds[[k]], ] %>% as.data.frame()
  test <- df.bn [-flds[[k]], ] %>% as.data.frame()
  
  doParallel::registerDoParallel(7)
  ############
  
  boot2 <- boot.strength(train,
                      R = 200,
                      algorithm = "hc",
                      algorithm.args = list (blacklist = bl))

  #############
  
  avg2 <-  averaged.network(boot2, threshold = 0.5)
  fit2 <-  bn.fit (avg2, train, method = "mle")
  
  num.var <- test %>%
    select_if (is.numeric) %>%
    names ()
  
  corr.df =  structure(numeric(length (num.var)), names = num.var)
  
  for (n in num.var) {
      corr.df[n] = cor(predict(fit2, 
                               data = test, 
                               node = n, 
                               method = "bayes-lw"),
                       test[n])
  }
  
  corr.df.list[[k]] <- corr.df
  

}

corr.df <- bind_cols (corr.df.list) %>%
  apply (1, mean)

names (corr.df) <- num.var
corr.df
       area         age    duration   pain_base   func_base severe_base 
 0.06639855 -0.10427296  0.03138296  0.21201146  0.45468078  0.49379270 
   dep_base     pain_1m     func_1m   severe_1m     pain_3m     func_3m 
 0.33910836  0.68501290  0.79584542  0.57758982  0.78845325  0.69547839 
  severe_3m     pain_6m     func_6m   severe_6m    pain_12m    func_12m 
 0.79161182  0.70549565  0.85728936  0.79530070  0.64397620  0.80991103 
 severe_12m   medn_base    uln_base   radn_base   neck_base     ct_base 
 0.67490796  0.76113173  0.58105758  0.74690423  0.70459492  0.68785777 
    ta_base 
 0.75301214 

Save data


sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252 
[2] LC_CTYPE=English_United Kingdom.1252   
[3] LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.1252    

attached base packages:
[1] grid      parallel  stats     graphics  grDevices utils     datasets 
[8] methods   base     

other attached packages:
 [1] bnviewer_0.1.6      Rgraphviz_2.34.0    graph_1.68.0       
 [4] BiocGenerics_0.36.0 doParallel_1.0.16   iterators_1.0.13   
 [7] foreach_1.5.1       caret_6.0-86        lattice_0.20-41    
[10] bnlearn_4.6.1       forcats_0.5.0       stringr_1.4.0      
[13] dplyr_1.0.2         purrr_0.3.4         readr_1.4.0        
[16] tidyr_1.1.2         tibble_3.0.4        ggplot2_3.3.3      
[19] tidyverse_1.3.0    

loaded via a namespace (and not attached):
 [1] nlme_3.1-151         fs_1.5.0             lubridate_1.7.9.2   
 [4] httr_1.4.2           rprojroot_2.0.2      tools_4.0.2         
 [7] backports_1.2.1      R6_2.5.0             rpart_4.1-15        
[10] DBI_1.1.0            colorspace_2.0-0     nnet_7.3-14         
[13] withr_2.3.0          tidyselect_1.1.0     compiler_4.0.2      
[16] git2r_0.27.1         cli_2.2.0            rvest_0.3.6         
[19] xml2_1.3.2           scales_1.1.1         digest_0.6.27       
[22] rmarkdown_2.6        pkgconfig_2.0.3      htmltools_0.5.0     
[25] dbplyr_2.0.0         htmlwidgets_1.5.3    rlang_0.4.10        
[28] readxl_1.3.1         rstudioapi_0.13      visNetwork_2.0.9    
[31] generics_0.1.0       jsonlite_1.7.2       ModelMetrics_1.2.2.2
[34] magrittr_2.0.1       Matrix_1.2-18        Rcpp_1.0.6          
[37] munsell_0.5.0        fansi_0.4.1          lifecycle_0.2.0     
[40] stringi_1.5.3        whisker_0.4          pROC_1.16.2         
[43] yaml_2.2.1           MASS_7.3-53          plyr_1.8.6          
[46] recipes_0.1.15       promises_1.1.1       crayon_1.3.4        
[49] haven_2.3.1          splines_4.0.2        hms_0.5.3           
[52] knitr_1.30           pillar_1.4.7         igraph_1.2.6        
[55] reshape2_1.4.4       codetools_0.2-18     stats4_4.0.2        
[58] reprex_0.3.0         glue_1.4.2           evaluate_0.14       
[61] data.table_1.14.0    modelr_0.1.8         vctrs_0.3.6         
[64] httpuv_1.5.4         cellranger_1.1.0     gtable_0.3.0        
[67] assertthat_0.2.1     xfun_0.20            gower_0.2.2         
[70] prodlim_2019.11.13   broom_0.7.4.9000     later_1.1.0.1       
[73] class_7.3-17         survival_3.2-7       timeDate_3043.102   
[76] workflowr_1.6.2      lava_1.6.8.1         ellipsis_0.3.1      
[79] ipred_0.9-9