# ---------------------------------------------------------------------------
# recompute_reference.R  (workflow: r-training-exercises-for-sas-programmers)
# Reproduces: Reference counts for the exercise answers: safety denominators, TEAE and serious TEAE subjects and events by arm (CSR Tables 14-5.01 and 14-5.02), Fisher p-values with the right TRTAN codes.
# Usage: Rscript recompute_reference.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: adam_adsl.xpt; adam_adae.xpt
#   Download the unmodified files from the public CDISC pilot repository:
#   https://github.com/cdisc-org/sdtm-adam-pilot-project  (folder updated-pilot-submission-package/900172/m5/)
#   (datasets as .xpt files).
# Expected output: see expected_output/recompute_reference_output.txt in this workflow's folder.
# Packages: dplyr 1.2.1, haven 2.5.5. Tested with R 4.6.1 on Windows.
#   Install what is missing with install.packages(c(...)); no private library path is needed.
# Licence: code MIT (see README.md in the scripts folder). Data: CDISC SDTM/ADaM Pilot Project (CDISCPILOT01),
# credited to CDISC, used unmodified under the CDISC terms of use. The data are not included here.
# Logic is unchanged from the version that produced the saved output; only path handling and this header were changed.
# ---------------------------------------------------------------------------
args <- commandArgs(trailingOnly = TRUE)
data_dir <- if (length(args) >= 1) args[1] else "."   # folder holding the CDISC pilot .xpt files
script_dir <- local({ f <- sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE))
                      if (length(f)) dirname(normalizePath(f[1])) else "." })   # folder holding this script
suppressMessages({library(haven);library(dplyr)})
adsl<-read_xpt(file.path(data_dir, "adam_adsl.xpt")); adae<-read_xpt(file.path(data_dir, "adam_adae.xpt"))
den <- adsl %>% filter(SAFFL=="Y") %>% count(TRT01AN, name="N"); print(den)
t <- adae %>% filter(TRTEMFL=="Y")
cat("Table 14-5.01 any TEAE: subjects and events by TRTAN\n")
print(t %>% group_by(TRTAN) %>% summarise(subj=n_distinct(USUBJID), events=n()))
s <- t %>% filter(AESER=="Y")
cat("Table 14-5.02 any serious TEAE\n")
print(s %>% group_by(TRTAN) %>% summarise(subj=n_distinct(USUBJID), events=n()))
for (a in c(54,81)) { 
 ev <- adsl %>% filter(SAFFL=="Y", TRT01AN %in% c(0,a)) %>% mutate(E=USUBJID %in% s$USUBJID)
 print(c(arm=a, p=fisher.test(table(ev$TRT01AN, ev$E))$p.value)) }
cat("As written in SAS: TRTAN in (0,2), (0,1):", sum(adsl$TRT01AN %in% c(1,2)), "rows match\n")
