# Initiate start-up file
source(file.path(rprojroot::find_root("DESCRIPTION"), "inst/startup.R"))
# Working directory requires write permission
if(file.access(".", 2) != 0){
  warning(
    "The working directory '", normalizePath("."), "' is not writable.\n",
    "Please change it to a location with write permission."
  )
}
knitr::opts_chunk$set(echo = TRUE)

# CRAN package, please using install.packages() to install
library(haven) 
library(dplyr)
library(ggplot2)
library(cowplot)
library(visR)

# Propitiatory Package, please refer appendix of ADRG to install 
library(pilot1wrappers)

Step 1: Read in data

adsl <- read_xpt(file.path(path$adam, "adsl.xpt"))
adtte <- read_xpt(file.path(path$adam, "adtte.xpt")) 

Step 2: Data preparation for endpoint TTDE

anl <- adsl %>% 
  dplyr::filter(
    SAFFL == "Y",
    STUDYID == "CDISCPILOT01"
  ) %>%
  dplyr::select(STUDYID, USUBJID, TRT01A) %>%
  dplyr::inner_join(
    filter(
      adtte, PARAMCD == "TTDE", STUDYID == "CDISCPILOT01"
    ) %>% select(STUDYID, USUBJID, AVAL, CNSR, PARAM, PARAMCD),
    by = c("STUDYID", "USUBJID")
  ) %>%
  dplyr::mutate(
    TRT01A = factor(TRT01A, levels = c("Placebo", "Xanomeline Low Dose",  "Xanomeline High Dose"))
  )

Step 3: Kaplan-Meier Plot and Save to Output

# estimate survival
surv_mod <- visR::estimate_KM(data = anl, strata = "TRT01A")
## Warning: `estimate_KM()` was deprecated in visR 0.4.0.
##  Please use `ggsurvfit::ggsurvfit()` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
# save plot
ggplot2::theme_set(theme_bw())

pdf.options(reset = TRUE, onefile = FALSE)

pdf(file.path(path$output, "tlf-kmplot.pdf"))

KM <- visR::visr(surv_mod,
           y_label = "Probability of event\n",
           x_label = "Time to First Dermatologic Event (Days)",
           y_ticks = seq(0,1,0.10)) %>%
    add_CNSR() %>%
    add_CI()
## Warning: `visr.survfit()` was deprecated in visR 0.4.0.
##  Please use `ggsurvfit::ggsurvfit()` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
KM <- KM + 
    ggplot2::geom_hline(yintercept=0.5, linetype = "dashed")

KM <- KM %>%
    visR::add_risktable(group = "statlist")

title <- cowplot::ggdraw() + 
  cowplot::draw_label(
    "KM plot for Time to First Dermatologic Event: Safety population\n",
    fontfamily = "sans",
    fontface = "bold",
    size=10
  ) 

caption <- cowplot::ggdraw() + 
  cowplot::draw_label(
    paste0("\nProgram: tlf_kmplot.Rmd [", Sys.time(), "]"),
    fontfamily = "sans",
    size=10
  ) 

KM <- cowplot::plot_grid(
  title, KM, caption,
  ncol = 1,
  rel_heights = c(0.1,0.8,0.1)
)

print(KM)
dev.off()
## agg_png 
##       2