Last updated: 2022-04-13

Checks: 7 0

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.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

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 696614c. 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/

Untracked files:
    Untracked:  Untitled/
    Untracked:  code/sem_mi.R
    Untracked:  data/Data SP-FMS-PF-EXP Study for Bernard.sav
    Untracked:  output/dat_imp.RDS
    Untracked:  output/res2.RDS

Unstaged changes:
    Modified:   analysis/2-bn_analysis.Rmd
    Modified:   analysis/4-TTH.Rmd
    Modified:   output/res.RDS

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/5-fms.Rmd) and HTML (docs/5-fms.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 696614c bernard-liew 2022-04-13 tidied fms analysis

Load package

rm (list = ls())
# Helper
library (tidyverse)
library (skimr)
library (flextable)
library (officer)
library (arsenal)
library (kableExtra)
library (mice)
library (rstatix)

# Parallel
library (doParallel)

# BN
library (bnlearn)
library (Rgraphviz)

#SEM
library (lavaan)
library (semPlot)
library (semptools)
library (semTools)

Load data

df <- rio::import("data/Data SP-FMS-PF-EXP Study for Bernard.sav") 

df <- map_df (df, function(x) {attributes(x) <- NULL;x})

Explore data

#skim (df)

miss_row <- apply(df, 1, function(x) sum(is.na(x)))

df2 <- df [(miss_row/ncol(df)) < 0.5, ] 

Descriptives

meanNsd_transform <- function (x) {

  m <- round (x[[1]][1], 2)
  s <- round (x[[1]][2], 2)

  m_s <- paste0(m, "(", s, ")")

  return (m_s)
}

tab1 <- tableby ( ~. , data = df2, digits = 2, digits.p = 2) %>%
  as.data.frame() %>%
  filter (!term %in% c("Nmiss", "range")) %>%
  dplyr::select (-c(group.term:term, variable.type, Total)) 


tab2 <-  tab1[-seq (1, 61, 2),]
tab2$label <- c("Age(years)",
                "Weight (kg)",
                "Height (m)",
                "Bmi",
                "Numbers of years diagnosed",
                "Mean pain",
                "Worst pain",
                "Pain activity",
                "Pain extent ventral",
                "Pain extent Dorsal",
                "PPT mastoid",
                "PPT trapezius",
                "PPT rlbow",
                "PPT hand",
                "PPT posterior iliac",
                "PPT trochanter",
                "PPT knee",
                "PPT tibialis",
                "TUG",
                "FIQ",
                "FHAQ",
                "EQ5DL",
                "LANSS",
                "Pain detect",
                "CSI",
                "HADS anxiety",
                "HADS depression",
                "Vigilance",
                "Catastotrophizing",
                "Fear",
                "Sleep")


  

for(row in 1:nrow(tab2)) {
    tab2[row, 2] <- meanNsd_transform (tab2[row, 2])
}

tab2[,2] <- unlist (tab2[,2])


# colnames (tab2) <- c ("Variables", 
#                       "Summary value")
# 
# my_path <- paste0("../manuscript_fms/table1",
#                   ".docx")
# 
# ft <- flextable(tab2) %>%
#   set_caption(caption = " Table 1.Baseline descriptive characteristics of cohort") %>%
#   autofit()
# 
# my_doc <- read_docx()  %>%
#   body_add_flextable(ft)
# 
# print (my_doc, target = my_path)

Change names

new_names <- c(
  "age",
  "wt",
  "ht",
  "bmi",
  "yrsDx",
  "meanP",
  "worstP",
  "Pact",
  "PextDor",
  "PextVent",
  "PPTmast",
  "PPTtrapz",
  "PPTelb",
  "PPThand",
  "PPTiliac",
  "PPTtroc",
  "PPTknee",
  "PPTtib",
  "tug",
  "fiq",
  "fhaq",
  "eq5d",
  "lanss",
  "painDetect",
  "csi",
  "anx",
  "dep",
  "vigil",
  "catas",
  "fear",
  "sleep"
  )

names (df2) <- new_names
res <- readRDS("output/res2.RDS")
list2env(res,globalenv())
<environment: R_GlobalEnv>

Impute

#dat_imp <-  mice::mice(df2, m = 20, seed = 155, maxit = 30, meth = "rf")

# saveRDS(dat_imp,
#         "output/dat_imp.RDS")

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

plot (dat_imp)

df3 <- mice::complete(dat_imp, "all") %>%
  map( ~ .x %>%
         mutate_if (is.numeric, scale, center = TRUE, scale = TRUE) %>%
         dplyr::select (-c(wt, ht, meanP, eq5d, fhaq, age, bmi)))

Correlations

c <- cor(df3[[1]], method = "pearson", use = "complete.obs")
corrplot::corrplot(c, type = "upper", order = "hclust", 
         tl.col = "black", tl.srt = 45)

Measurement model using CFA

Model

Plot

cfa0_dummy <- cfa (cfa_form0, 
                   data = df3[[1]], 
                   std.lv = FALSE, 
                   auto.fix.first = TRUE, 
                   estimator = "MLR",
                   se = "robust.huber.white")

fig <- semPlotModel(cfa0_dummy)
x = data.frame (summary (cfa0))
fig@Pars$est <- x$est[1: length (fig@Pars$est)]

fig2 <- semPaths (fig, 
          what = "path", 
          whatLabels= "est",
          nCharNodes = 0,
          freeStyle = c( "black","1"),
          edge.label.cex = 0.5,
          residuals = FALSE)

indicator_order  <- c("PPTmast", "PPTtrapz","PPTelb", "PPThand", 
                      "PPTiliac" , "PPTtroc" , "PPTknee" , "PPTtib", 
                      "PextDor" , "PextVent", "Pact" , "worstP",
                      "lanss", "painDetect" , "csi", 
                      "anx" , "dep" , "vigil" , "catas" , "fear")

indicator_factor <- c("Sensitivity", "Sensitivity","Sensitivity", "Sensitivity", 
                      "Sensitivity", "Sensitivity","Sensitivity", "Sensitivity",  
                      "Severity" , "Severity", "Severity" , "Severity",
                      "Sensitization", "Sensitization" , "Sensitization", 
                      "Distress" , "Distress" , "Distress" , "Distress" , "Distress")


factor_layout <- matrix(c(NA, "Sensitivity", NA, NA, NA, "Severity",
                          NA,NA, NA, NA, NA, NA,
                          NA,NA, NA, NA, NA, NA,
                          NA,"Sensitization", NA, NA, NA, "Distress"),
                          byrow = TRUE, 4, 6)

factor_point_to <-  matrix(c(NA,"up", NA, NA, NA, "right",
                          NA,NA, NA, NA, NA, NA,
                          NA,NA, NA, NA, NA, NA,
                          NA,"down", NA, NA, NA, "down"),
                          byrow = TRUE, 4, 6)

indicator_spread <- c(Sensitivity = 5,
                    Severity = 4,
                    Sensitization = 4,
                    Distress = 4)

indicator_push <- c(Sensitivity =2,
                    Severity = 2,
                    Sensitization = 2,
                    Distress = 2)

fig_mod <- set_sem_layout(fig2, 
                     indicator_order = indicator_order,
                     indicator_factor = indicator_factor,
                     factor_layout = factor_layout,
                     factor_point_to = factor_point_to,
                     indicator_push = indicator_push,
                     indicator_spread = indicator_spread)
plot(fig_mod)



# png ("../manuscript_fms/fig1.png", height = 10, width = 15, units = "in", res = 100)
# plot(fig_mod)
# dev.off()

Bootstrap

l2 = c(LETTERS, sort(do.call("paste0", expand.grid(LETTERS, LETTERS))))

Mediation

Montecarlo bootstrap coefficients

myParams <- c("a1", "b1", "a2", "b2", "a3", "b3", "c")

(coefs <- coef(m0)[myParams]) 
(AsyCovMat <- vcov(m0)[myParams, myParams])

expres <- c(  a1 = "a1",
              a2 = "a2",
              a3 = "a3",
              b1 = "b1",
              b2 = "b2",
              b3 = "b3",
              c = "c",
              ind1 = "a1*b1",
              ind2 = "a2*b2",
              ind3 = "a3*b3",
              total = "c + (a1*b1) + (a2*b2) + (a3*b3)",
              contrast1 = "ind1-ind2",
              contrast2 = "ind1-ind3",
              contrast3 = "ind2-ind3")


m0_coef <- monteCarloCI(expr = expres,
                        ACM = AsyCovMat,
                        coefs = coefs)
m0_coef <- m0_coef %>%
  rownames_to_column("label")

Plot

m0_dummy <- sem (sem_form0, 
                   data = df3[[1]], 
                   std.lv = FALSE, 
                   auto.fix.first = TRUE, 
                   estimator = "MLR",
                   se = "robust.huber.white")

fig <- semPlotModel(m0_dummy )

x = data.frame (summary (m0))
fig@Pars$est <- x$est[1: length (fig@Pars$est)]

manifest_var <- c("PPTmast", "PPTtrapz","PPTelb", "PPThand", "PPTiliac" , "PPTtroc" , "PPTknee" , "PPTtib", "PextDor" , "PextVent", "Pact" , "yrsDx" , "worstP", "lanss", "painDetect" , "csi", "anx" , "dep" , "vigil" , "catas" , "fear")

fig2 <- drop_nodes(fig, manifest_var)

fig2 <- semPaths (fig2, 
          what = "path", 
          whatLabels= "est",
          fixedStyle = c( "white","0"),
          freeStyle = c( "black","1"),
          residuals = FALSE,
          nCharNodes = 0,
          curveAdjacent = c("cov", "reg"),
          curvature = 2,
          intercept = TRUE,
          edge.label.cex = 0.8,
          nodeLabels = c("Sleep", "Sens", "Severity", "Senstz", "Distress"),
          exoCov = FALSE,
          color = list (lat = "grey", man = "white"),
          edge.label.position = 0.5)

indicator_order  <- c("Sleep", "Sens", "Severity", "Senstz", "Distress")

indicator_factor <- c("Sleep", "Sens", "Severity", "Senstz", "Distress")

factor_layout <- matrix(c(NA,NA, NA, NA, "Sens", NA,  NA, 
                          NA, NA, NA,NA, NA, NA,NA,
                          NA,NA, NA, "Senstz", NA,  NA, NA,
                          NA,NA, NA, NA, NA,  NA, NA, 
                          "Distress",NA, NA, NA, NA,  NA, "Severity", 
                          NA,NA, NA, NA, NA,  NA, NA, 
                          NA,NA, NA, NA, NA,  NA, NA,
                          NA,NA, NA, NA, "Sleep", NA,  NA),
                          byrow = TRUE, 8, 7)

factor_point_to <-  matrix(c(NA,NA, NA, NA, "left", NA,  NA, 
                          NA, NA, NA,NA, NA, NA,NA,
                          NA,NA, NA, "left", NA,  NA, NA,
                          NA,NA, NA, NA, NA,  NA, NA, 
                          "left",NA, NA, NA, NA,  NA, "left", 
                          NA,NA, NA, NA, NA,  NA, NA, 
                          NA,NA, NA, NA, NA,  NA, NA,
                          NA,NA, NA, NA, "left", NA,  NA),
                          byrow = TRUE, 8, 7)

fig_mod <- set_sem_layout(fig2, 
                     indicator_order = indicator_order,
                     indicator_factor = indicator_factor,
                     factor_layout = factor_layout,
                     factor_point_to = factor_point_to)
plot(fig_mod)


# png ("../manuscript_fms/fig2.png", height = 10, width = 15, units = "in", res = 100)
# plot(fig_mod)
# dev.off()

Report

# Export lavaan table
param_ex<- summary (m0, standardized = TRUE) %>%
  filter (op != "~~") %>%
  rename (DV = lhs,
          IV = rhs,
          Coef = est,
          SE = se,
          Pval = pvalue) %>%
  data.frame () %>%
  left_join(m0_coef, by = c("label")) %>%
  rename (`LB` = ci.lower,
          `UB` = ci.upper) %>%
  mutate_if (is.numeric, round, 3) %>%
  mutate (Sig = ifelse (Pval < 0.05, "s", "ns")) %>%
  mutate (Type = case_when(
    op == "=~" ~ "LV",
    op == "~" ~ "Reg",
    TRUE ~ "Med"
  )) %>%
  dplyr::select ( DV, IV, Coef, SE, `LB`, `UB`,Pval, Sig, Type) %>%
  mutate (Coef = as.numeric (Coef)) 

param_ex$DV[28:34] <- c("Indirect 1", "Indirect 2", "Indirect 3",
                        "Total", "Indirect Contrast 1", "Indirect Contrast 2", "Indirect Contrast 3")
param_ex$IV[28:34] <- c("Sensitization", "Sensitivity", "Sleep",
                        " ", 
                        "Indirect 1 - Indirect 2", "Indirect 1 - Indirect 3", "Indirect 2 - Indirect 3")

param_ex <- param_ex%>%
  mutate (Type = factor (Type, levels = c("Med", "Reg", "LV"))) %>%
  arrange (Type, DV)


# Export lavaan table

# my_path <- paste0("../manuscript_fms/table2", 
#                   ".docx")
# 
# ft <- flextable(param_ex) %>%
#   set_caption(caption = " Table 2.Parameter estimates for model") %>%
#   autofit() 
# 
# my_doc <- read_docx()  %>% 
#   body_add_flextable(ft)
# 
# print (my_doc, target = my_path)

Sensitivity analysis

Save data

res <- list (cfa0 = cfa0,
             cfa0_coef = cfa0_coef,
             m0 = m0,
             m0_coef = m0_coef,
             m1 = m1,
             m1_coef = m1_coef,
             df = df,
             dat_imp = dat_imp,
             df3 = df3,
             my.sa = my.sa,
             boot = boot)

saveRDS (res,
         "output/res2.RDS")

sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

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] semTools_0.5-5      semptools_0.2.9.3   semPlot_1.1.2      
 [4] lavaan_0.6-9        Rgraphviz_2.38.0    graph_1.72.0       
 [7] BiocGenerics_0.40.0 bnlearn_4.7         doParallel_1.0.16  
[10] iterators_1.0.13    foreach_1.5.1       rstatix_0.7.0      
[13] mice_3.13.0         kableExtra_1.3.4    arsenal_3.6.3      
[16] officer_0.4.0       flextable_0.6.9     skimr_2.1.3        
[19] forcats_0.5.1       stringr_1.4.0       dplyr_1.0.7        
[22] purrr_0.3.4         readr_2.0.2         tidyr_1.1.4        
[25] tibble_3.1.6        ggplot2_3.3.5       tidyverse_1.3.1    

loaded via a namespace (and not attached):
  [1] utf8_1.2.2          tidyselect_1.1.1    lme4_1.1-27.1      
  [4] htmlwidgets_1.5.4   munsell_0.5.0       codetools_0.2-18   
  [7] withr_2.5.0         colorspace_2.0-2    highr_0.9          
 [10] OpenMx_2.19.8       knitr_1.37          uuid_1.0-2         
 [13] rstudioapi_0.13     stats4_4.1.2        mi_1.0             
 [16] emmeans_1.7.0       git2r_0.28.0        repr_1.1.3         
 [19] mnormt_2.0.2        rprojroot_2.0.2     TH.data_1.1-0      
 [22] coda_0.19-4         vctrs_0.3.8         generics_0.1.1     
 [25] xfun_0.30           R6_2.5.1            arm_1.12-2         
 [28] assertthat_0.2.1    promises_1.2.0.1    scales_1.1.1       
 [31] multcomp_1.4-17     nnet_7.3-16         gtable_0.3.0       
 [34] sandwich_3.0-1      workflowr_1.6.2     rlang_1.0.2        
 [37] systemfonts_1.0.3   splines_4.1.2       broom_0.7.12       
 [40] checkmate_2.0.0     yaml_2.2.1          reshape2_1.4.4     
 [43] abind_1.4-5         modelr_0.1.8        backports_1.4.1    
 [46] httpuv_1.6.3        Hmisc_4.6-0         tools_4.1.2        
 [49] psych_2.1.9         ellipsis_0.3.2      jquerylib_0.1.4    
 [52] RColorBrewer_1.1-2  Rsolnp_1.16         Rcpp_1.0.8         
 [55] plyr_1.8.6          base64enc_0.1-3     rockchalk_1.8.144  
 [58] rpart_4.1-15        pbapply_1.5-0       zoo_1.8-9          
 [61] qgraph_1.9          haven_2.4.3         cluster_2.1.2      
 [64] fs_1.5.0            magrittr_2.0.1      data.table_1.14.2  
 [67] openxlsx_4.2.4      reprex_2.0.1        truncnorm_1.0-8    
 [70] tmvnsim_1.0-2       mvtnorm_1.1-3       whisker_0.4        
 [73] hms_1.1.1           evaluate_0.14       xtable_1.8-4       
 [76] XML_3.99-0.8        rio_0.5.27          jpeg_0.1-9         
 [79] readxl_1.3.1        gridExtra_2.3       compiler_4.1.2     
 [82] crayon_1.4.2        minqa_1.2.4         htmltools_0.5.2    
 [85] corpcor_1.6.10      later_1.3.0         tzdb_0.2.0         
 [88] Formula_1.2-4       RcppParallel_5.1.4  lubridate_1.8.0    
 [91] DBI_1.1.1           corrplot_0.91       kutils_1.70        
 [94] dbplyr_2.1.1        MASS_7.3-54         boot_1.3-28        
 [97] Matrix_1.3-4        car_3.0-12          cli_3.2.0          
[100] igraph_1.2.7        pkgconfig_2.0.3     sem_3.1-13         
[103] foreign_0.8-81      xml2_1.3.2          pbivnorm_0.6.0     
[106] svglite_2.0.0       bslib_0.3.1         webshot_0.5.2      
[109] estimability_1.3    rvest_1.0.2         digest_0.6.28      
[112] rmarkdown_2.11      cellranger_1.1.0    htmlTable_2.3.0    
[115] lisrelToR_0.1.4     gdtools_0.2.3       curl_4.3.2         
[118] gtools_3.9.2        nloptr_1.2.2.2      lifecycle_1.0.1    
[121] nlme_3.1-153        glasso_1.11         jsonlite_1.8.0     
[124] carData_3.0-4       viridisLite_0.4.0   fansi_0.5.0        
[127] pillar_1.6.4        lattice_0.20-45     fastmap_1.1.0      
[130] httr_1.4.2          survival_3.2-13     glue_1.6.1         
[133] zip_2.2.0           fdrtool_1.2.17      png_0.1-7          
[136] stringi_1.7.5       sass_0.4.0          regsem_1.8.0       
[139] latticeExtra_0.6-29