# ---------------------------------------------------------------------------
# bad_run_data_facts.R  (workflow: r-training-exercises-for-sas-programmers)
# Reproduces: Facts about the pilot data that the weaker answer got wrong: ADTTE parameters and censoring, variable names, AESEV values, arm names. Also reports whether the pharmaverseadam package is installed on the machine running it.
# Usage: Rscript bad_run_data_facts.R <data_dir>
#   data_dir = folder containing the input files below (default: current folder).
# Input files: adam_adsl.xpt; adam_adae.xpt; adam_adtte.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/bad_run_data_facts_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)})
src <- paste0(sub("/+$", "", data_dir), "/")
adsl<-read_xpt(paste0(src,"adam_adsl.xpt")); adae<-read_xpt(paste0(src,"adam_adae.xpt")); adtte<-read_xpt(paste0(src,"adam_adtte.xpt"))
cat("pharmaverseadam installed in rlib:", "pharmaverseadam" %in% rownames(installed.packages()), "\n")
print(adtte %>% count(PARAMCD,PARAM)); print(table(adtte$CNSR,useNA="a"))
cat("TRT01P in adtte:", "TRT01P" %in% names(adtte), " TRTP:", "TRTP" %in% names(adtte), "\n")
print(table(adsl$AGEGR1,useNA="a")); print(range(adsl$AGE))
print(table(adae$AESEV,useNA="a"))
cat("'SEVERE' in AESEV:", "SEVERE" %in% adae$AESEV, "\n")
cat("ADAE has TRT01A:", "TRT01A" %in% names(adae), "\n")
cat("ADAE SAFFL in adae:", "SAFFL" %in% names(adae),"\n")
print(table(adsl$TRT01P))
