# ---------------------------------------------------------------------------
# bad_run_check.R  (workflow: r-training-exercises-for-sas-programmers)
# Reproduces: Runs the weaker answer's Exercise 5 and Exercise 7 code on the pilot files to show the errors (TRT01A is not in ADAE; TRT01P is not in ADTTE).
# Usage: Rscript bad_run_check.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_check_output.txt in this workflow's folder.
# Packages: dplyr 1.2.1, haven 2.5.5, survival 3.8.6, tidyr 1.3.2. Tested with R 4.6.1 on Windows.
#   Install what is missing with install.packages(c(...)); no private library path is needed.
# Note: Uses the survival package (shipped with R).
# 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);library(tidyr)})
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("--- bad Exercise 5 (as written, on the pilot xpt files)\n")
r <- try({
big_n <- adsl |> filter(SAFFL == "Y") |> count(TRT01A, name = "N")
flag_summary <- function(df, label) df |> distinct(USUBJID, TRT01A) |> count(TRT01A, name = "n") |> mutate(row = label)
teae <- adae |> filter(TRTEMFL == "Y", SAFFL == "Y")
flag_summary(teae, "Any TEAE")})
cat("--- bad Exercise 7 (as written)\n")
r2 <- try({ library(survival); d <- adtte |> filter(PARAMCD == "TTDE") |> mutate(event = 1 - CNSR)
survfit(Surv(AVAL, event) ~ TRT01P, data = d)})
