{
 "id": "r-training-exercises-for-sas-programmers",
 "title": "Six R exercises for SAS programmers, with every model solution run against the SAS output",
 "study": {
  "name": "CDISCPILOT01 (CDISC SDTM/ADaM Pilot Project, xanomeline TTS in Alzheimer's disease)",
  "source_url": "https://github.com/cdisc-org/sdtm-adam-pilot-project",
  "licence_note": "Programs, datasets and CSR are CDISC Pilot Project materials, used unmodified and attributed to CDISC under the Terms of Use in the repository README (no modification, no sale of the data, attribution required). The study is a CDISC mock submission with fictional dates. The team-task list in this example is invented and bannered. Not legal advice."
 },
 "task": "INVENTED for this example, not a real document: the list of \"team tasks\" (T1 to T4) that the exercises are tied to. Everything else is real CDISC Pilot material. Ask an AI for six R exercises for SAS programmers, built from two real SAS programs (adam_adae.sas and adam_at14-5-02.sas) and the pilot xpt files, each with a model solution; then run every model solution in R and compare it with the SAS-produced adam_adae.xpt and with CSR Tables 14-5.01 and 14-5.02. Result of the run on 2026-10-21: five of the six solutions ran unedited and passed their checks; Exercise 5 (Fisher tests) ran but gave p = 1 twice because the treatment codes in the data are 0, 54 and 81, not 0, 1 and 2 as the model and the SAS program assume. With the codes changed it gave p = 0.243 and 0.494, matching the CSR.",
 "time_to_try_minutes": "About 60 minutes (estimate, not measured): paste the excerpt, generate the exercises, then run each solution in R and compare",
 "good": {
  "input_excerpt": "SOURCE (real): CDISC SDTM/ADaM Pilot Project, study CDISCPILOT01 (xanomeline TTS in Alzheimer's disease; CDISC mock submission, fictional dates). Files in the repository https://github.com/cdisc-org/sdtm-adam-pilot-project, retrieved 2026-10-19, used unmodified; credit CDISC.\n\nFILES available to the learners (SAS transport files, to be read in R with haven::read_xpt; all in the working directory):\n- sdtm_ae.xpt: 1191 rows, 35 columns: STUDYID DOMAIN USUBJID AESEQ AESPID AETERM AELLT AELLTCD AEDECOD AEPTCD AEHLT AEHLTCD AEHLGT AEHLGTCD AEBODSYS AEBDSYCD AESOC AESOCCD AESEV AESER AEACN AEREL AEOUT AESCAN AESCONG AESDISAB AESDTH AESHOSP AESLIFE AESOD AEDTC AESTDTC AEENDTC AESTDY AEENDY\n- adam_adsl.xpt: 254 rows, 48 columns: STUDYID USUBJID SUBJID SITEID SITEGR1 ARM TRT01P TRT01PN TRT01A TRT01AN TRTSDT TRTEDT TRTDUR AVGDD CUMDOSE AGE AGEGR1 AGEGR1N AGEU RACE RACEN SEX ETHNIC SAFFL ITTFL EFFFL COMP8FL COMP16FL COMP24FL DISCONFL DSRAEFL DTHFL BMIBL BMIBLGR1 HEIGHTBL WEIGHTBL EDUCLVL DISONSDT DURDIS DURDSGR1 VISIT1DT RFSTDTC RFENDTC VISNUMEN RFENDT DCDECOD DCREASCD MMSETOT\n- adam_adae.xpt: the ADAE dataset that the SAS program adam_adae.sas produced, 1191 rows, 55 columns: STUDYID SITEID USUBJID TRTA TRTAN AGE AGEGR1 AGEGR1N RACE RACEN SEX SAFFL TRTSDT TRTEDT ASTDT ASTDTF ASTDY AENDT AENDY ADURN ADURU AETERM AELLT AELLTCD AEDECOD AEPTCD AEHLT AEHLTCD AEHLGT AEHLGTCD AEBODSYS AESOC AESOCCD AESEV AESER AESCAN AESCONG AESDISAB AESDTH AESHOSP AESLIFE AESOD AEREL AEACN AEOUT AESEQ TRTEMFL AOCCFL AOCCSFL AOCCPFL AOCC02FL AOCC03FL AOCC04FL CQ01NAM AOCC01FL\n- adam_adtte.xpt: 254 rows, 26 columns: STUDYID SITEID USUBJID AGE AGEGR1 AGEGR1N RACE RACEN SEX TRTSDT TRTEDT TRTDUR TRTP TRTA TRTAN PARAM PARAMCD AVAL STARTDT ADT CNSR EVNTDESC SRCDOM SRCVAR SRCSEQ SAFFL (no SAS program for it was supplied)\nThe SAS programs use libnames set in a setup.sas file that is not available (sdtmnew = SDTM, adamnew = ADaM).\n\nINVENTED for this example, not a real document. \"Team tasks\" (a made-up list so the exercises can be tied to day-to-day work; the real Pilot Project has no such list):\nT1. Rebuild a derived dataset in R and show that it matches the SAS-produced one.\nT2. Reproduce the counts in an adverse event table (subjects, percent, number of events) for each treatment group.\nT3. Read SAS transport files in R and check dates, missing values and keys.\nT4. Compare treatment groups with Fisher's exact test.\nEND OF INVENTED SECTION.\n\nREAL SAS CODE (CDISC Pilot Project, shortened as marked). Quoted unchanged except that blank lines and whole-line comments were removed.\n=== adam_adae.sas (part 1; blank lines and whole-line comments removed) ===\nproc sort data=sdtmnew.AE OUT=AE;\nby USUBJID AESEQ;\nrun;\ndata AE;\n\tset AE;\n\tby USUBJID AESEQ;\n\tASTDT=input(strip(AESTDTC),?? yymmdd10.);\n\tAENDT=input(strip(AEENDTC),?? yymmdd10.);\n\tif ASTDT>.z and AENDT>.z then ADUR=AENDT-ASTDT+1;\n\tformat ASTDT AENDT DATE9.;\nrun;\n\nproc sort data=adamnew.ADSL OUT=TEMP(keep=SITEID USUBJID TRT01A TRT01AN AGE AGEGR1 AGEGR1N RACE RACEN SEX SAFFL\nTRTSDT TRTEDT RENAME=(TRT01A=TRTA TRT01AN=TRTAN));\nby USUBJID;\nrun;\n\n=== adam_adae.sas (part 2, continues; comments and blank lines removed) ===\ndata AE;\n\tmerge AE(in=inAE) TEMP;\n\tby USUBJID;\n\tif inAE;\n\tif ASTDT=. and length(AESTDTC)=7 /*and input(strip(substr(AESTDTC,1,4)),?? best.)=year(TRTSDT)*/ then do;\n\t\tASTDT=input(compress(AESTDTC||'-01'), yymmdd10.);\n\t\tASTDTF='D';\n\tend;\n\tlength CQ01NAM $25;\n\tIF ASTDT>=TRTSDT>.z then ASTDY=ASTDT-TRTSDT+1;\n\tELSE IF TRTSDT>ASTDT>.z then ASTDY=ASTDT-TRTSDT;\n\tIF AENDT>=TRTSDT>.z then AENDY=AENDT-TRTSDT+1;\n\tELSE IF TRTSDT>AENDT>.z then AENDY=AENDT-TRTSDT;\n\tIF ASTDT>.z and TRTSDT>.z then ANLSTDY=ASTDT-TRTSDT+1;\n\tIF (ASTDT>=TRTSDT>.z) then TRTEMFL='Y';\n\tELSE TRTEMFL='N';\n\tIF index(aedecod,'APPLICATION') or\n    index(aedecod,'DERMATITIS') or\n    index(aedecod,'ERYTHEMA') or\n    index(aedecod,'BLISTER') or\n    (aebodsys='SKIN AND SUBCUTANEOUS TISSUE DISORDERS' and aedecod not in ('COLD SWEAT','HYPERHIDROSIS','ALOPECIA'))\n    then  CQ01NAM='DERMATOLOGIC EVENTS';\nrun;\n\n=== adam_adae.sas (macro and calls) ===\n%macro flagfrst(inds=,sortvars=, invar=,outvar=,outds=, ser=, derm=);\nproc sort data=&inds out=ds01;\n     by usubjid &sortvars ASTDT;\n\t where trtemfl='Y'\n               %if &invar ne %then and &invar ne '';\n               %if &ser ne %then and aeser='Y';\n\t\t\t   %if &derm ne %then and CQ01NAM='DERMATOLOGIC EVENTS';\n\t ;\nrun;\ndata ds02(keep=usubjid &outvar aeseq);\n     set ds01;\n         by usubjid &sortvars ASTDT;\n\t if %if &invar= %then first.usubjid; %else first.&invar; then do ;\n        &outvar='Y';\n        output;\n\t end;\nrun;\nproc sort data=ds02 out=&outds;\n     by usubjid aeseq;\nrun;\n%mend flagfrst;\n%flagfrst(inds=ae,sortvars=,invar=,outvar=AOCCFL,outds=aea);\n%flagfrst(inds=ae,sortvars=aebodsys,invar=aebodsys,outvar=AOCCSFL,outds=aeb);\n%flagfrst(inds=ae,sortvars=aebodsys aedecod,invar=aedecod,outvar=AOCCPFL,outds=aec);\n%flagfrst(inds=ae,sortvars=,invar=,outvar=AOCC02FL,outds=saea, ser=Y);\n%flagfrst(inds=ae,sortvars=aebodsys,invar=aebodsys,outvar=AOCC03FL,outds=saeb,ser=Y);\n%flagfrst(inds=ae,sortvars=aebodsys aedecod,invar=aedecod,outvar=AOCC04FL,outds=saec,ser=Y);\n%flagfrst(inds=ae,sortvars=,invar=,outvar=AOCC01FL,outds=derm, ser=,derm=Y);\n\n=== adam_at14-5-02.sas (PROC SQL header, denominators, preferred-term counts; blank lines removed; the SOC-level and subject-level count blocks, which repeat the same pattern, are left out) ===\nPROC SQL;\nCREATE TABLE DENOM AS\nSELECT COUNT(distinct usubjid) as denom, TRT01AN as TRTAN\nFROM ADSL(where=(SAFFL='Y'))\nGROUP BY TRTAN\nORDER BY TRTAN;\n/* COUNT UNIQUE SUBJECTS BY SOC AND PREFERRED TERM AND TREATMENT */\nCREATE TABLE AEPTD AS\nSELECT COUNT(distinct usubjid) AS count, AEBODSYS, AEDECOD, TRTAN\nFROM ADAE(where=(TRTEMFL='Y' and AESER='Y'))\nGROUP BY TRTAN, AEBODSYS, AEDECOD\nORDER BY TRTAN, AEBODSYS, AEDECOD;\n** COUNT ALL EVENTS BY SOC AND PREFERRED TERM AND TREATMENT **;\nCREATE TABLE AEPTA AS\nSELECT COUNT(usubjid) AS events, AEBODSYS, AEDECOD, TRTAN\nFROM ADAE(where=(TRTEMFL='Y' and AESER='Y'))\nGROUP BY TRTAN, AEBODSYS, AEDECOD\nORDER BY TRTAN, AEBODSYS, AEDECOD;\n** GET RESULTS AT PTLEVEL **;\ncreate table RESULTPT as select a.*, 3 as SUMMARYLEVEL, b.DENOM, c.events,\nstrip(put(count,best.))||' ('||strip(put((count/denom)*100,8.1))||'%) ['||strip(put(events,best.))||']'\nas RESULT LENGTH=50\nfrom AEPTD as A left join DENOM as b\non a.TRTAN=b.TRTAN\nleft join AEPTA as c\non a.TRTAN=c.TRTAN and a.AEBODSYS=c.AEBODSYS and a.AEDECOD=c.AEDECOD\norder by AEBODSYS, AEDECOD, TRTAN;\n\n=== adam_at14-5-02.sas (subject-level Fisher test block, blank lines removed) ===\n** SUBJECT LEVEL**;\nproc sql;\ncreate table BACKBONE2 as select * from\n(select distinct USUBJID, TRT01AN as TRTAN from ADSL(where=(SAFFL='Y')));\ncreate table HADEVENT2 as select distinct STUDYID, USUBJID, TRTAN\nfrom ADAE(where=(TRTEMFL='Y' and AESER='Y'));\ncreate table FISHER2 as select a.USUBJID, a.TRTAN,\ncase when STUDYID='CDISCPILOT01' then 1\nelse 0\nend as EVENT\nfrom BACKBONE2 a left join HADEVENT2 b\non a.USUBJID=b.USUBJID and a.TRTAN=b.TRTAN\norder by a.TRTAN;\nquit;\n** HIGH DOSE VERSUS PLACEBO **;\nproc freq data=FISHER2;\nwhere TRTAN in (0,2);\ntable TRTAN*EVENT/exact;\nods output FishersExact=F1SUB(where=(Name1='XP2_FISH'));\nrun;\n** LOW DOSE VERSUS PLACEBO **;\nproc freq data=FISHER2;\nwhere TRTAN in (0,1);\ntable TRTAN*EVENT/exact;\nods output FishersExact=F2SUB(where=(Name1='XP2_FISH'));\nrun;",
  "prompt": "Write six R exercises for SAS programmers who are learning R, based only on the files and SAS programs above. Order them from easiest to hardest. Give each exercise:\n1. Task: the text the learner sees, one paragraph.\n2. SAS maps to: the SAS statement(s) it replaces.\n3. Hint: one.\n4. Model solution: complete R code (haven, dplyr, tidyr, stringr), runnable as written when the xpt files are in the working directory.\n5. CHECK: what the solution's result must equal (a column or count in adam_adae.xpt, or a result the table program would give).\n6. Team task: T1 to T4, or none.\nRules: do not state any numeric result you cannot get from the text above; write \"compare with ...\" instead. Name every place where SAS and R behave differently. At the end, list what you could not tell from the text that the team would have to supply.",
  "output": "# Six R exercises for SAS programmers (CDISCPILOT01)\n\nSource: CDISC SDTM/ADaM Pilot Project, https://github.com/cdisc-org/sdtm-adam-pilot-project (credit CDISC). All files are used unmodified. Assumed packages: haven, dplyr (1.1.0 or later), tidyr, stringr. All files are in the working directory.\n\nI have not run any of this code. Every CHECK that depends on a number says \"compare with ...\". The only numbers stated are the row counts given in the text (1191, 254, 1191).\n\nTreatment codes: the Fisher block compares TRTAN 0 with 2 (\"HIGH DOSE VERSUS PLACEBO\") and 0 with 1 (\"LOW DOSE VERSUS PLACEBO\"). So I read 0 as placebo, 1 as low dose and 2 as high dose. This is inferred from the comments, not stated.\n\n---\n\n## Exercise 1 (easiest): Read the transport files and check keys, dates and blanks\n\n**Task:** Read sdtm_ae.xpt, adam_adsl.xpt and adam_adae.xpt into R. Confirm the row counts given in the data description. Sort AE by USUBJID and AESEQ. Count duplicate USUBJID values in ADSL, duplicate USUBJID+AESEQ keys in AE, AE subjects missing from ADSL, and ADAE rows with no matching AE row. Show how long the AESTDTC and AEENDTC texts are, count blank character variables in AE, and report the R class of the four date columns of ADAE.\n\n**SAS maps to:** `sdtmnew.AE` / `adamnew.ADSL` libname access, and `proc sort data=sdtmnew.AE out=AE; by USUBJID AESEQ;`\n\n**Hint:** `read_xpt()` returns a tibble. A blank SAS character value arrives as `\"\"`, not `NA`, so test for both.\n\n**Model solution:**\n```r\nlibrary(haven); library(dplyr); library(tidyr); library(stringr)\n\nae   <- read_xpt(\"sdtm_ae.xpt\")\nadsl <- read_xpt(\"adam_adsl.xpt\")\nadae <- read_xpt(\"adam_adae.xpt\")\n\nstopifnot(nrow(ae) == 1191, nrow(adsl) == 254, nrow(adae) == 1191)\n\nae <- ae %>% arrange(USUBJID, AESEQ)\n\nkeys <- list(\n  adsl_duplicate_usubjid  = adsl %>% count(USUBJID) %>% filter(n > 1) %>% nrow(),\n  ae_duplicate_key        = ae %>% count(USUBJID, AESEQ) %>% filter(n > 1) %>% nrow(),\n  ae_subjects_not_in_adsl = ae %>% anti_join(adsl, by = \"USUBJID\") %>% nrow(),\n  adae_rows_not_in_ae     = adae %>% anti_join(ae, by = c(\"USUBJID\", \"AESEQ\")) %>% nrow()\n)\nprint(keys)\n\nprint(ae %>% count(length_AESTDTC = nchar(str_trim(AESTDTC))))\nprint(ae %>% count(length_AEENDTC = nchar(str_trim(AEENDTC))))\n\nblanks <- ae %>%\n  summarise(across(where(is.character), ~ sum(is.na(.x) | .x == \"\"))) %>%\n  pivot_longer(everything(), names_to = \"variable\", values_to = \"n_blank\") %>%\n  filter(n_blank > 0)\nprint(blanks)\n\nprint(sapply(adae[c(\"ASTDT\", \"AENDT\", \"TRTSDT\", \"TRTEDT\")], function(x) class(x)[1]))\n```\n\n**CHECK:**\n- The three row counts must equal 1191, 254 and 1191. `stopifnot` enforces this.\n- The four counts in `keys` are expected to be 0 if the keys are unique and consistent. The text does not say, so compare with 0.\n- The four ADAE date columns should be class `Date`.\n- Compare the length tables with the date handling in the SAS code. It handles blank texts (the `??` modifier) and 7-character texts (month only).\n\n**SAS and R differences:**\n- R is case sensitive. The SAS code writes `usubjid`, `aedecod`; here the names must be upper case as in the files.\n- Blank character is `\"\"` in R, not `NA`.\n- SAS dates (days since 1960) arrive as `Date` (origin 1970), converted by haven.\n- `arrange()` puts `NA` last and (dplyr 1.1.0 or later) sorts text in C locale. SAS sorts missing first and text in its collating sequence. Base `order()` and `sort()` use the locale and can differ.\n- `proc sort` writes a new dataset. `arrange()` returns a new tibble and does not change the file.\n\n**Team task:** T3\n\n---\n\n## Exercise 2: Convert character dates and derive duration\n\n**Task:** From sdtm_ae.xpt, build ASTDT and AENDT from the character dates AESTDTC and AEENDTC. Use only complete ISO dates, and give anything else a missing value. Also build ADUR as AENDT minus ASTDT plus 1, only when both dates exist. Merge your result with the AE rows of adam_adae.xpt by USUBJID and AESEQ. Count mismatches for AENDT, and for ASTDT where your ASTDT is not missing. Also count rows where your ASTDT is missing but ADAE has a date, and show their AESTDTC lengths.\n\n**SAS maps to:** `ASTDT=input(strip(AESTDTC),?? yymmdd10.); AENDT=...; if ASTDT>.z and AENDT>.z then ADUR=AENDT-ASTDT+1; format ... DATE9.;`\n\n**Hint:** `as.Date(x, format = \"%Y-%m-%d\")` returns `NA` for text that is not a full date. Subtracting two dates gives a difftime, so wrap it in `as.numeric()`.\n\n**Model solution:**\n```r\nlibrary(haven); library(dplyr); library(tidyr); library(stringr)\n\nae   <- read_xpt(\"sdtm_ae.xpt\")\nadae <- read_xpt(\"adam_adae.xpt\")\n\nsame <- function(a, b) {\n  a <- as.numeric(a); b <- as.numeric(b)\n  (is.na(a) & is.na(b)) | (!is.na(a) & !is.na(b) & a == b)\n}\n\nae2 <- ae %>%\n  arrange(USUBJID, AESEQ) %>%\n  mutate(\n    ASTDT = as.Date(str_sub(str_trim(AESTDTC), 1, 10), format = \"%Y-%m-%d\"),\n    AENDT = as.Date(str_sub(str_trim(AEENDTC), 1, 10), format = \"%Y-%m-%d\"),\n    ADUR  = if_else(!is.na(ASTDT) & !is.na(AENDT),\n                    as.numeric(AENDT - ASTDT) + 1, NA_real_)\n  )\n\ncmp <- ae2 %>%\n  select(USUBJID, AESEQ, AESTDTC, ASTDT, AENDT, ADUR) %>%\n  inner_join(adae %>% select(USUBJID, AESEQ, ASTDT_sas = ASTDT,\n                             AENDT_sas = AENDT, ADURN),\n             by = c(\"USUBJID\", \"AESEQ\"))\nstopifnot(nrow(cmp) == 1191)\n\nresult <- list(\n  AENDT_mismatches = sum(!same(cmp$AENDT, cmp$AENDT_sas)),\n  ASTDT_mismatches_where_derived = sum(!is.na(cmp$ASTDT) &\n                                       !same(cmp$ASTDT, cmp$ASTDT_sas)),\n  ASTDT_missing_here_but_present_in_ADAE = sum(is.na(cmp$ASTDT) & !is.na(cmp$ASTDT_sas)),\n  ADUR_vs_ADURN_mismatches = sum(!is.na(cmp$ADUR) & !same(cmp$ADUR, cmp$ADURN))\n)\nprint(result)\nprint(cmp %>% filter(is.na(ASTDT), !is.na(ASTDT_sas)) %>%\n        count(length_AESTDTC = nchar(str_trim(AESTDTC))))\n```\n\n**CHECK:**\n- `AENDT_mismatches` and `ASTDT_mismatches_where_derived` must equal 0. Compare with 0.\n- Rows with `ASTDT_missing_here_but_present_in_ADAE` should be the month-only dates that Exercise 3 imputes. The length table should show only 7 if that is so; compare.\n- `ADUR_vs_ADURN_mismatches` is informational. ADAE has no ADUR, only ADURN and ADURU, and their derivation is not in the text. Differences may come from code not shown, for example imputed start dates.\n\n**SAS and R differences:**\n- The `??` modifier hides invalid-date notes in the SAS log. R silently returns `NA`, so count the `NA`s yourself.\n- SAS `yymmdd10.` reads exactly 10 characters. `str_sub(..., 1, 10)` imitates this. `as.Date()` with `format` also ignores trailing characters.\n- SAS dates are plain numbers, so `AENDT-ASTDT` is a number. In R, `Date - Date` is a difftime, hence `as.numeric()`.\n- `NA` propagates in R. The SAS test `ASTDT>.z` becomes `!is.na(ASTDT)`.\n\n**Team task:** T1\n\n---\n\n## Exercise 3: Merge ADSL, impute the month-only start date, derive study days and TEAE flag\n\n**Task:** Extend Exercise 2. Join the subject variables SITEID, TRT01A (as TRTA), TRT01AN (as TRTAN), AGE, AGEGR1, AGEGR1N, RACE, RACEN, SEX, SAFFL, TRTSDT and TRTEDT from ADSL onto the AE rows, keeping every AE row. If ASTDT is missing and AESTDTC has exactly 7 characters, set ASTDT to the first of that month and set ASTDTF to \"D\". Derive ASTDY and AENDY (there is no day 0: dates on or after TRTSDT count from 1, earlier dates are negative) and TRTEMFL (\"Y\" if ASTDT is on or after TRTSDT, otherwise \"N\"). Compare all derived columns with adam_adae.xpt row by row.\n\n**SAS maps to:** `data AE; merge AE(in=inAE) TEMP; by USUBJID; if inAE;` and the whole block `if ASTDT=. and length(AESTDTC)=7 ... ASTDTF='D'` through `TRTEMFL`.\n\n**Hint:** Write each SAS chained comparison such as `ASTDT>=TRTSDT>.z` as separate parts joined by `&`: `!is.na(ASTDT) & !is.na(TRTSDT) & ASTDT >= TRTSDT`. Use `as.Date(..., format = \"%Y-%m-%d\")` so that a text that is not a date gives `NA` instead of an error.\n\n**Model solution:**\n```r\nlibrary(haven); library(dplyr); library(tidyr); library(stringr)\n\nae   <- read_xpt(\"sdtm_ae.xpt\")\nadsl <- read_xpt(\"adam_adsl.xpt\")\nadae <- read_xpt(\"adam_adae.xpt\")\n\nnorm <- function(x) if (is.character(x)) coalesce(trimws(x), \"\") else as.numeric(x)\nsame <- function(a, b) {\n  a <- norm(a); b <- norm(b)\n  (is.na(a) & is.na(b)) | (!is.na(a) & !is.na(b) & a == b)\n}\n\ntemp <- adsl %>%\n  select(SITEID, USUBJID, TRTA = TRT01A, TRTAN = TRT01AN, AGE, AGEGR1, AGEGR1N,\n         RACE, RACEN, SEX, SAFFL, TRTSDT, TRTEDT)\nstopifnot(!anyDuplicated(temp$USUBJID))   # many-to-one, like the SAS merge\n\nteae <- ae %>%\n  arrange(USUBJID, AESEQ) %>%\n  mutate(\n    sdtc  = str_trim(AESTDTC),\n    ASTDT = as.Date(str_sub(sdtc, 1, 10), format = \"%Y-%m-%d\"),\n    AENDT = as.Date(str_sub(str_trim(AEENDTC), 1, 10), format = \"%Y-%m-%d\")\n  ) %>%\n  left_join(temp, by = \"USUBJID\") %>%\n  mutate(\n    partial = is.na(ASTDT) & coalesce(nchar(sdtc) == 7, FALSE),\n    ASTDT   = if_else(partial,\n                      as.Date(str_c(sdtc, \"-01\"), format = \"%Y-%m-%d\"), ASTDT),\n    ASTDTF  = if_else(partial, \"D\", \"\"),\n    ASTDY = case_when(\n      !is.na(ASTDT) & !is.na(TRTSDT) & ASTDT >= TRTSDT ~ as.numeric(ASTDT - TRTSDT) + 1,\n      !is.na(ASTDT) & !is.na(TRTSDT) & TRTSDT > ASTDT  ~ as.numeric(ASTDT - TRTSDT),\n      .default = NA_real_),\n    AENDY = case_when(\n      !is.na(AENDT) & !is.na(TRTSDT) & AENDT >= TRTSDT ~ as.numeric(AENDT - TRTSDT) + 1,\n      !is.na(AENDT) & !is.na(TRTSDT) & TRTSDT > AENDT  ~ as.numeric(AENDT - TRTSDT),\n      .default = NA_real_),\n    TRTEMFL = if_else(!is.na(ASTDT) & !is.na(TRTSDT) & ASTDT >= TRTSDT, \"Y\", \"N\")\n  )\n\ncols <- c(\"SITEID\", \"TRTA\", \"TRTAN\", \"AGE\", \"AGEGR1\", \"AGEGR1N\", \"RACE\", \"RACEN\",\n          \"SEX\", \"SAFFL\", \"TRTSDT\", \"TRTEDT\", \"ASTDT\", \"ASTDTF\", \"ASTDY\",\n          \"AENDT\", \"AENDY\", \"TRTEMFL\")\n\nchk <- teae %>%\n  select(USUBJID, AESEQ, all_of(cols)) %>%\n  inner_join(adae %>% select(USUBJID, AESEQ, all_of(cols)),\n             by = c(\"USUBJID\", \"AESEQ\"), suffix = c(\"\", \".sas\"))\nstopifnot(nrow(teae) == 1191, nrow(chk) == 1191)\n\nmismatches <- sapply(cols, function(v) sum(!same(chk[[v]], chk[[paste0(v, \".sas\")]])))\nprint(mismatches)\nprint(count(teae, ASTDTF, TRTEMFL))\n```\n\n**CHECK:**\n- 1191 rows after the join. This is stated: AE and ADAE both have 1191 rows, so no AE row is lost.\n- Every element of `mismatches` should be 0 against ADAE columns SITEID, TRTA, TRTAN, AGE, AGEGR1, AGEGR1N, RACE, RACEN, SEX, SAFFL, TRTSDT, TRTEDT, ASTDT, ASTDTF, ASTDY, AENDT, AENDY and TRTEMFL. Compare with 0.\n- If any are not 0, the cause may be code that is not shown, for example other imputation.\n- The SAS code also derives ANLSTDY, but ADAE has no such column, so it cannot be checked.\n- The `count(ASTDTF, TRTEMFL)` table is informational. Compare with the SAS output.\n\n**SAS and R differences:**\n- SAS `merge ... by ... if inAE` is replaced by `left_join()`. No sorting is needed in R.\n- If ADSL had duplicate USUBJID, SAS would repeat the values. `left_join` would multiply the AE rows. The `stopifnot` guards this.\n- In SAS, missing is smaller than every number, so `ASTDT>=TRTSDT` is TRUE when TRTSDT is missing. This is why the code adds `>.z`. In R a comparison with `NA` gives `NA`, so test with `is.na()` explicitly.\n- `if_else()` returns `NA` for an `NA` condition. `case_when()` treats `NA` as \"not matched\". Do not expect SAS fall-through behaviour from either.\n- A SAS character missing value is blank. Here it is `\"\"`; `NA` from a join must be turned into `\"\"`.\n- SAS `length()` of a blank returns 1. `nchar(\"\")` returns 0. This makes no difference for the test `= 7`.\n- SAS `length CQ01NAM $25` fixes the text length. R has no lengths.\n\n**Team task:** T1\n\n---\n\n## Exercise 4: Count subjects, percent and events for serious treatment-emergent AEs by preferred term\n\n**Task:** Using adam_adae.xpt and adam_adsl.xpt, recreate the denominators (distinct subjects with SAFFL = \"Y\" per TRT01AN) and, for each treatment, system organ class (AEBODSYS) and preferred term (AEDECOD), the number of distinct subjects, the number of events, and the string \"n (x.x%) [events]\". Use treatment-emergent (TRTEMFL = \"Y\") serious (AESER = \"Y\") events only. Then check your subject counts against the first-occurrence flag AOCC04FL in ADAE.\n\n**SAS maps to:** The `proc sql` blocks `DENOM`, `AEPTD`, `AEPTA` and `RESULTPT` (`count(distinct usubjid)`, `count(usubjid)`, `left join`, `put(..., 8.1)`).\n\n**Hint:** `count(distinct x)` is `n_distinct(x)` and `count(x)` of a non-missing key is `n()`. SAS rounds a half upwards, R may not, so use a small rounding helper before formatting.\n\n**Model solution:**\n```r\nlibrary(haven); library(dplyr); library(tidyr); library(stringr)\n\nadsl <- read_xpt(\"adam_adsl.xpt\")\nadae <- read_xpt(\"adam_adae.xpt\")\n\nsas_round <- function(x, d = 1) sign(x) * floor(abs(x) * 10^d + 0.5 + 1e-9) / 10^d\n\ndenom <- adsl %>%\n  filter(SAFFL == \"Y\") %>%\n  group_by(TRTAN = TRT01AN) %>%\n  summarise(denom = n_distinct(USUBJID), .groups = \"drop\") %>%\n  arrange(TRTAN)\n\nresultpt <- adae %>%\n  filter(TRTEMFL == \"Y\", AESER == \"Y\") %>%\n  group_by(TRTAN, AEBODSYS, AEDECOD) %>%\n  summarise(count = n_distinct(USUBJID), events = n(), .groups = \"drop\") %>%\n  left_join(denom, by = \"TRTAN\") %>%\n  mutate(SUMMARYLEVEL = 3L,\n         pct    = sas_round(100 * count / denom, 1),\n         RESULT = sprintf(\"%d (%.1f%%) [%d]\", count, pct, events)) %>%\n  arrange(AEBODSYS, AEDECOD, TRTAN)\n\nprint(denom)\nprint(resultpt, n = 30)\n\n# CHECK against AOCC04FL (first serious TEAE per subject, SOC and PT)\nflag_counts <- adae %>%\n  filter(AOCC04FL == \"Y\") %>%\n  count(TRTAN, AEBODSYS, AEDECOD, name = \"n_flag\")\ncmp <- resultpt %>%\n  filter(AEDECOD != \"\") %>%\n  full_join(flag_counts, by = c(\"TRTAN\", \"AEBODSYS\", \"AEDECOD\"))\ncat(\"cells where count differs from AOCC04FL:\",\n    sum(is.na(cmp$count) | is.na(cmp$n_flag) | cmp$count != cmp$n_flag), \"\\n\")\n```\n\n**CHECK:**\n- For every treatment, SOC and PT cell, `count` must equal the number of ADAE rows with AOCC04FL = \"Y\" in that cell, because AOCC04FL flags the first serious TEAE per subject, SOC and PT. The last line must print 0 (compare with 0).\n- `denom` must equal the SAFFL = \"Y\" subject counts per TRT01AN. The numbers are not in the text; compare with the SAS table output. The total over all groups cannot exceed 254.\n- `RESULT` strings must equal the SAS `RESULT` column at summary level 3. The SAS output is not supplied; compare with it.\n\n**SAS and R differences:**\n- SQL `count()` ignores NULL. `n()` counts rows, so a missing USUBJID would behave differently. Check that USUBJID is never blank.\n- `put(x, 8.1)` rounds halves away from zero. `sprintf(\"%.1f\")` and `round()` follow binary floating point and can round to even (for example `round(0.25, 1)` is 0.2). `sas_round()` imitates SAS. Compare for any differing cell.\n- `best.` has no R equivalent. Integer counts in `sprintf(\"%d\")` give the same text.\n- `group_by` keeps `\"\"` as a group, as SQL `group by` keeps blanks. A real `NA` would also form its own group in both.\n- The `order by` clause in SQL becomes `arrange()`. Text sorting is C locale in dplyr 1.1.0 or later.\n- The SOC-level and subject-level count blocks are not in the text and are not reproduced.\n\n**Team task:** T2\n\n---\n\n## Exercise 5: Fisher's exact test, each dose against placebo, on subject level\n\n**Task:** Build a subject-level dataset of all safety-population subjects (SAFFL = \"Y\") from ADSL with TRTAN = TRT01AN. Mark EVENT = 1 for subjects who have at least one treatment-emergent serious AE in ADAE, otherwise 0. Run Fisher's exact test on treatment (0 against 2, then 0 against 1) by EVENT, and print the 2 by 2 tables and the p-values. Check the number of events per treatment against the flag AOCC02FL.\n\n**SAS maps to:** `BACKBONE2`, `HADEVENT2`, `FISHER2` (the `left join` and `case when STUDYID=...`) and the two `proc freq ... table TRTAN*EVENT/exact;` steps with `ods output FishersExact=...`.\n\n**Hint:** In the SAS code `STUDYID` comes from the right-hand table of the join, so it is non-missing only for subjects with an event. In R, join an explicit `EVENT = 1L` and replace `NA` with 0. Build the table with factor levels so that it stays 2 by 2.\n\n**Model solution:**\n```r\nlibrary(haven); library(dplyr); library(tidyr); library(stringr)\n\nadsl <- read_xpt(\"adam_adsl.xpt\")\nadae <- read_xpt(\"adam_adae.xpt\")\n\nbackbone <- adsl %>% filter(SAFFL == \"Y\") %>% distinct(USUBJID, TRTAN = TRT01AN)\n\nhadevent <- adae %>%\n  filter(TRTEMFL == \"Y\", AESER == \"Y\") %>%\n  distinct(USUBJID, TRTAN) %>%\n  mutate(EVENT = 1L)\n\nfisher2 <- backbone %>%\n  left_join(hadevent, by = c(\"USUBJID\", \"TRTAN\")) %>%\n  mutate(EVENT = coalesce(EVENT, 0L)) %>%\n  arrange(TRTAN)\n\nrun_fisher <- function(d, trts, label) {\n  x   <- d %>% filter(TRTAN %in% trts)\n  tab <- table(TRTAN = factor(x$TRTAN, levels = trts),\n               EVENT = factor(x$EVENT, levels = c(0, 1)))\n  print(label); print(tab)\n  tibble(comparison = label, p_two_sided = fisher.test(tab)$p.value)\n}\n\nres <- bind_rows(\n  run_fisher(fisher2, c(0, 2), \"high dose vs placebo\"),\n  run_fisher(fisher2, c(0, 1), \"low dose vs placebo\")\n)\nprint(res)\n\n# CHECK: events per treatment vs AOCC02FL\nprint(fisher2 %>% group_by(TRTAN) %>% summarise(events = sum(EVENT)))\nprint(adae %>% filter(AOCC02FL == \"Y\", SAFFL == \"Y\") %>% count(TRTAN))\n```\n\n**CHECK:**\n- Per treatment, `sum(EVENT)` must equal the count of ADAE rows with AOCC02FL = \"Y\" (SAFFL = \"Y\"), because AOCC02FL flags the first serious TEAE per subject. Compare the two printed tables.\n- The two p-values must equal the SAS Fisher p-values in F1SUB (high dose against placebo) and F2SUB (low dose against placebo), the rows with Name1 = 'XP2_FISH'. That name suggests the two-sided p-value; confirm in the SAS output. The SAS output is not supplied, so compare with it.\n- The 2 by 2 cell counts must also agree with the SAS `proc freq` tables.\n\n**SAS and R differences:**\n- `proc freq` with a zero column drops it and gives a 1-column table. The factor levels in `table()` force a 2 by 2 table, and `fisher.test` then gives p = 1.\n- `fisher.test()` uses a relative tolerance of 1e-7 when summing table probabilities, as SAS does. Differences are possible only for ties near that tolerance. `fisher.test` also returns a conditional odds ratio estimate, which is not in the SAS dataset kept by the program.\n- The SAS trick `case when STUDYID='CDISCPILOT01'` relies on missing values from a left join. In R it is clearer and safer to join an explicit flag.\n- R's `table(TRTAN, EVENT)` has the same orientation as `TRTAN*EVENT`, but the two-sided p-value does not depend on it.\n\n**Team task:** T4\n\n---\n\n## Exercise 6 (hardest): Replace the %flagfrst macro and the CQ01NAM flag with an R function\n\n**Task:** Write one R function that does what the SAS macro `%flagfrst` does. It selects treatment-emergent rows (TRTEMFL = \"Y\"), optionally drops rows where a chosen variable is blank, optionally keeps only serious rows or only dermatologic events, orders by ASTDT, takes the first row per subject (plus the chosen grouping variables), and returns USUBJID, AESEQ and the flag \"Y\". First derive CQ01NAM (\"DERMATOLOGIC EVENTS\") from AEDECOD and AEBODSYS with the SAS rules. Call the function seven times to build AOCCFL, AOCCSFL, AOCCPFL, AOCC02FL, AOCC03FL, AOCC04FL and AOCC01FL, join them back, and compare them and CQ01NAM with adam_adae.xpt. Start from the inputs already in ADAE (TRTEMFL, ASTDT, AESER, AEDECOD, AEBODSYS).\n\n**SAS maps to:** The `IF index(aedecod,...) ... then CQ01NAM='DERMATOLOGIC EVENTS'` statement, the whole `%macro flagfrst ... %mend` and its seven calls.\n\n**Hint:** Pass column names as strings and use `.data[[name]]` for the filter, and `group_by(across(all_of(...)))` for the group. The BY group for `first.&invar` is USUBJID plus the sort variables, so that is the grouping. Use `fixed()` in `str_detect()` because SAS `index()` is a plain, case-sensitive substring search.\n\n**Model solution:**\n```r\nlibrary(haven); library(dplyr); library(tidyr); library(stringr)\n\nadae <- read_xpt(\"adam_adae.xpt\")\n\nnorm <- function(x) coalesce(trimws(as.character(x)), \"\")\n\nbase <- adae %>%\n  select(USUBJID, AESEQ, TRTEMFL, ASTDT, AESER, AEDECOD, AEBODSYS) %>%\n  mutate(\n    hit = str_detect(AEDECOD, fixed(\"APPLICATION\")) |\n          str_detect(AEDECOD, fixed(\"DERMATITIS\"))  |\n          str_detect(AEDECOD, fixed(\"ERYTHEMA\"))    |\n          str_detect(AEDECOD, fixed(\"BLISTER\"))     |\n          (AEBODSYS == \"SKIN AND SUBCUTANEOUS TISSUE DISORDERS\" &\n           !(AEDECOD %in% c(\"COLD SWEAT\", \"HYPERHIDROSIS\", \"ALOPECIA\"))),\n    CQ01NAM = if_else(coalesce(hit, FALSE), \"DERMATOLOGIC EVENTS\", \"\")\n  ) %>%\n  select(-hit)\n\nflag_first <- function(data, outvar, sortvars = character(), invar = NULL,\n                       ser = FALSE, derm = FALSE) {\n  d <- data %>% filter(TRTEMFL == \"Y\")\n  if (!is.null(invar)) d <- d %>% filter(.data[[invar]] != \"\")\n  if (ser)  d <- d %>% filter(AESER == \"Y\")\n  if (derm) d <- d %>% filter(CQ01NAM == \"DERMATOLOGIC EVENTS\")\n  d %>%\n    arrange(ASTDT, AESEQ) %>%                       # ties keep AESEQ order\n    group_by(across(all_of(c(\"USUBJID\", sortvars)))) %>%\n    slice(1) %>%\n    ungroup() %>%\n    transmute(USUBJID, AESEQ, !!outvar := \"Y\")\n}\n\nspecs <- list(\n  list(outvar = \"AOCCFL\",   sortvars = character(),                invar = NULL),\n  list(outvar = \"AOCCSFL\",  sortvars = \"AEBODSYS\",                 invar = \"AEBODSYS\"),\n  list(outvar = \"AOCCPFL\",  sortvars = c(\"AEBODSYS\", \"AEDECOD\"),   invar = \"AEDECOD\"),\n  list(outvar = \"AOCC02FL\", sortvars = character(),                invar = NULL, ser = TRUE),\n  list(outvar = \"AOCC03FL\", sortvars = \"AEBODSYS\",                 invar = \"AEBODSYS\", ser = TRUE),\n  list(outvar = \"AOCC04FL\", sortvars = c(\"AEBODSYS\", \"AEDECOD\"),   invar = \"AEDECOD\", ser = TRUE),\n  list(outvar = \"AOCC01FL\", sortvars = character(),                invar = NULL, derm = TRUE)\n)\n\nres <- base\nfor (s in specs) {\n  f   <- do.call(flag_first, c(list(data = base), s))\n  res <- res %>%\n    left_join(f, by = c(\"USUBJID\", \"AESEQ\")) %>%\n    mutate(!!s$outvar := coalesce(.data[[s$outvar]], \"\"))\n}\n\nchk <- res %>%\n  select(USUBJID, AESEQ, CQ01NAM, all_of(sapply(specs, `[[`, \"outvar\"))) %>%\n  inner_join(adae %>% select(USUBJID, AESEQ, CQ01NAM,\n                             all_of(sapply(specs, `[[`, \"outvar\"))),\n             by = c(\"USUBJID\", \"AESEQ\"), suffix = c(\"\", \".sas\"))\nstopifnot(nrow(chk) == 1191)\n\nvars <- c(\"CQ01NAM\", sapply(specs, `[[`, \"outvar\"))\nprint(sapply(vars, function(v) sum(norm(chk[[v]]) != norm(chk[[paste0(v, \".sas\")]]))))\nprint(sapply(vars, function(v) sum(norm(chk[[v]]) != \"\")))\n```\n\n**CHECK:**\n- Each of the eight mismatch counts (CQ01NAM and the seven flags) must equal 0 when compared with adam_adae.xpt. Compare with 0.\n- The number of non-blank values per variable is informational. Compare with `table(adae$AOCC04FL)` and similar.\n- If ADAE stores unflagged rows as something other than blank (for example \"N\"), all mismatch counts for a flag will be large for that reason alone. Look at the values first.\n- The macro tests `%if &invar ne %then ...` with an empty right-hand side. A zero mismatch count confirms that it behaved as intended.\n\n**SAS and R differences:**\n- A SAS macro substitutes text before the code runs. An R function receives column names as strings and needs `.data[[name]]`.\n- `first.&invar` depends on a prior `proc sort` and BY statement. In R, `arrange()` plus `group_by()` plus `slice(1)` replaces both. Order within the groups does not matter for which row is kept, because ties are resolved by the ordering `ASTDT, AESEQ`.\n- SAS `index()` returns 0 for a blank string. `str_detect()` returns `FALSE` for `\"\"` and `NA` for `NA`, which is why the result is wrapped in `coalesce()`.\n- SAS compares text ignoring trailing blanks. R does not, so trim the text.\n- `NOT IN (...)` becomes `!(x %in% c(...))`. `%in%` never returns `NA`, but `==` can.\n- SAS flags absent from the merge are blank. After `left_join` they are `NA` and must be replaced with `\"\"`.\n\n**Team task:** T1\n\n---\n\n## What the text does not tell us, which the team must supply\n\n1. Whether AESTDTC and AEENDTC can contain a time part or other lengths. Exercise 1 shows the real lengths.\n2. The merge-back of the seven flag datasets into ADAE is not in the text. How unflagged rows are stored in adam_adae.xpt (blank or \"N\") must be confirmed.\n3. Whether adam_adae.sas contains more code than the two parts shown (for example imputation of AENDT). The text says the parts are shortened and continued. Any mismatch in Exercises 2, 3 and 6 may come from code not shown.\n4. How ADURN and ADURU in ADAE are derived. The text shows ADUR only, and ANLSTDY is derived but is not in the ADAE column list.\n5. All numeric results: the counts, denominators, percentages, events and Fisher p-values. The outputs of adam_at14-5-02.sas (the RESULTPT dataset and F1SUB and F2SUB) are not supplied.\n6. Whether Name1 'XP2_FISH' is the two-sided p-value.\n7. The table's title and population, and the labels of the TRTAN codes. They were inferred from the Fisher comments and the program name only.\n8. The SOC-level and subject-level count blocks of the table program, which are left out of the text.\n9. Whether USUBJID is unique in ADSL (254 rows) and USUBJID+AESEQ is unique in AE. The exercises test this but the text does not say it.\n10. Whether text values in the xpt files carry trailing blanks, and the R, dplyr, haven and SAS versions in use. The rounding and sorting notes assume dplyr 1.1.0 or later.\n11. The contents of setup.sas (libnames and options, for example locale).\n12. adam_adtte.xpt has no program in the text, so no exercise uses it.\n\n----------------------------------------------------------------------\nR RUN (added after the answer was saved; R 4.6.1, haven 2.5.5, dplyr 1.2.1; 2026-10-21). Each model solution was run unedited from the folder holding the xpt files. Scripts and console output: r-training-exercises-for-sas-programmers_Rrun/.\n\nExercise 1: ran. keys 0/0/0/0 (no duplicate USUBJID in ADSL, no duplicate USUBJID+AESEQ in AE, no orphans either way). AESTDTC lengths: 4 chars 11, 7 chars 15, 10 chars 1165. AEENDTC blank 473. Four ADAE date columns are class Date. PASS.\nExercise 2: ran. AENDT mismatches 0, ASTDT mismatches where derived 0, 15 rows missing here but present in ADAE (all 7-character month-only dates), ADUR vs ADURN mismatches 0. PASS.\nExercise 3: ran. All 18 compared columns, 0 mismatches against adam_adae.xpt (ASTDTF/TRTEMFL: blank+N 56, blank+Y 1120, D+N 9, D+Y 6). PASS.\nExercise 4: ran. Denominators 86 / 84 / 84. Three serious TEAE PT rows: PARTIAL SEIZURES WITH SECONDARY GENERALISATION (high 1 [1]), SYNCOPE (low 1 [1], high 1 [1]), all under NERVOUS SYSTEM DISORDERS. Cells differing from AOCC04FL: 0. PASS.\nExercise 5: ran, but the answer is wrong. TRTAN 0 vs 2 and 0 vs 1 give all-zero active rows and p = 1 for both comparisons, because TRTAN in the data is 0, 54 and 81. FAIL as written. With c(0, 81) and c(0, 54): high dose 2/84 vs 0/86 p = 0.243, low dose 1/84 vs 0/86 p = 0.494. PASS after the one-line change.\nExercise 6: ran. CQ01NAM and the seven AOCC flags: 8 of 8 mismatch counts are 0 against adam_adae.xpt (non-blank counts 493, 218, 550, 781, 3, 3, 3, 152). PASS.\n\nReference numbers (separate R and Python scripts, not the model's code): CSR Table 14-5.01 ANY BODY SYSTEM: 65 [281], 77 [412], 76 [433] = recomputed 65/281, 77/412, 76/433. CSR Table 14-5.02: placebo 0, low 1 (1.2%) [1], high 2 (2.4%) [2], Fisher 0.494 and 0.243 = recomputed 0, 1/1, 2/2, p = 0.4941 and 0.2427.\nCross-check with an earlier translation run (xcheck_*): ADAE rebuilt from SDTM AE and ADSL matches adam_adae.xpt, 0 differing columns (ADURN and ADURU exist in the xpt where the program has ADUR; ADUR equals ADURN).\nFinding about the SAS itself: adam_at14-5-02.sas filters TRTAN in (0,2) and (0,1). In the shipped data no ADSL row has TRT01AN 1 or 2, so those proc freq steps would see only placebo. The model copied the 0/1/2 coding.\n----------------------------------------------------------------------",
  "trim_note": "The answer part is the cold answer from a fresh subagent that saw only the input and prompt above, saved unmodified (it was told not to use tools; the tool list was not technically removed). The R RUN block was added afterwards by the builder from the saved console outputs. The SAS excerpt is the two programs with blank lines and whole-line comments removed and the SOC-level and subject-level count blocks of the table program left out; the full programs are in the CDISC repository. A first cold run in an earlier session was not retrieved; this is the second run and the only one saved. One model, one run each, not a rate."
 },
 "bad": {
  "input": "Can you make some R exercises for our SAS programmers? We use the CDISC pilot data (ADSL, ADAE, ADTTE) and have an AE table program. Make them match what the team does day to day, with solutions.",
  "output": "# R Exercises for SAS Programmers (CDISC Pilot: ADSL, ADAE, ADTTE)\n\n**Assumptions.** I haven't seen your AE table program, so exercises 5 and 6 use a standard TEAE summary layout. Swap in your own spec when you run them. I wrote the code against the pharmaverseadam versions of the CDISC pilot ADaM (`adsl`, `adae`, `adtte`). Variable names there are:\n- Population and treatment: SAFFL, TRT01A, TRT01P\n- Adverse events: TRTEMFL, AEBODSYS, AEDECOD, AESEV, AESER\n- Time to event: PARAMCD, AVAL, CNSR\n\nI haven't run any of this code. Please run it once before handing it out and fix any names that differ in your copy.\n\nSetup for all exercises:\n```r\ninstall.packages(c(\"tidyverse\", \"haven\", \"pharmaverseadam\", \"survival\", \"gt\"))\nlibrary(tidyverse)\nlibrary(haven)\nlibrary(survival)\nlibrary(pharmaverseadam)\n\nadsl  <- pharmaverseadam::adsl\nadae  <- pharmaverseadam::adae\nadtte <- pharmaverseadam::adtte\n# To read your own SAS files instead: adsl <- read_sas(\"adsl.sas7bdat\")\n```\n\n## SAS to R cheat sheet (hand this out first)\n\n| SAS | R (tidyverse) |\n|---|---|\n| `data x; set y; where a=1; run;` | `x <- y |> filter(a == 1)` |\n| `keep` / `drop` | `select()` |\n| `new = ...;` in a data step | `mutate()` |\n| `proc sort` | `arrange()` |\n| `proc sort nodupkey` | `distinct(col, .keep_all = TRUE)` |\n| `by` group processing, `first.` / `last.` | `group_by()` then `slice_head()` / `slice_tail()` |\n| `merge a(in=x) b(in=y); if x;` | `left_join(a, b, by = ...)` |\n| `proc freq` | `count()` and `group_by() |> summarise(n = n())` |\n| `proc means` | `summarise(mean(), sd(), median())` |\n| `proc transpose` | `pivot_wider()` / `pivot_longer()` |\n| `if/else if` | `case_when()` |\n| `.` (missing) | `NA`. Use `is.na()`, never `== NA`. |\n| `proc lifetest` | `survfit()` |\n| `proc phreg` | `coxph()` |\n\nGotchas to teach:\n- Missing values: `NA > 5` returns `NA`, not TRUE as in SAS where missing sorts lowest.\n- Many functions need `na.rm = TRUE`.\n- Data frames have no implicit row order unless you `arrange()`.\n- Joins do not require sorting.\n- There is no PDV (program data vector). Each verb works on the whole data frame.\n- Indexing starts at 1.\n- Character versus factor ordering affects table row order.\n\n---\n\n## Exercise 1: Read and inspect (proc contents / proc print)\n**Task.** (a) Show the structure of `adsl`. (b) How many subjects are in the safety population (SAFFL = \"Y\")? (c) Count subjects by TRT01A.\n\n**Solution.**\n```r\nglimpse(adsl)                         # proc contents\nadsl |> filter(SAFFL == \"Y\") |> nrow()\nadsl |> filter(SAFFL == \"Y\") |> count(TRT01A)   # proc freq\n```\n**Point.** `count()` replaces most simple `proc freq` calls. The pipe `|>` is the data-step flow.\n\n## Exercise 2: Derive variables (data step)\n**Task.** On ADSL, create AGEGR1N / AGEGR1 groups (<65, 65-80, >80) and a flag `ELDFL` = \"Y\" if AGE >= 75, else \"N\". Handle missing AGE.\n\n**Solution.**\n```r\nadsl2 <- adsl |>\n  mutate(\n    AGEGR1 = case_when(\n      is.na(AGE) ~ NA_character_,\n      AGE < 65   ~ \"<65\",\n      AGE <= 80  ~ \"65-80\",\n      TRUE       ~ \">80\"\n    ),\n    AGEGR1N = case_when(AGEGR1 == \"<65\" ~ 1, AGEGR1 == \"65-80\" ~ 2, AGEGR1 == \">80\" ~ 3),\n    ELDFL   = if_else(AGE >= 75, \"Y\", \"N\", missing = \"N\")\n  )\nadsl2 |> count(AGEGR1N, AGEGR1)\n```\n**Point.** `case_when` evaluates top to bottom like `if/else if`. Check the NA behavior explicitly.\n\n## Exercise 3: Merge ADSL onto ADAE (merge with IN=)\n**Task.** Bring ADSL's AGE, SEX, and RACE onto ADAE for safety-population subjects. Check for subjects in ADSL with no AEs.\n\n**Solution.**\n```r\nadae_m <- adae |>\n  select(-any_of(c(\"AGE\", \"SEX\", \"RACE\"))) |>\n  inner_join(adsl |> filter(SAFFL == \"Y\") |> select(USUBJID, AGE, SEX, RACE),\n             by = \"USUBJID\")\n\n# subjects with no AE (merge ... if a and not b)\nadsl |> filter(SAFFL == \"Y\") |> anti_join(adae, by = \"USUBJID\") |> nrow()\n```\n**Point.** Join types map to the IN= logic: `inner_join` is `if a and b`, `left_join` is `if a`, `anti_join` is `if a and not b`. Watch for duplicate column names, which become `.x` and `.y`.\n\n## Exercise 4: First occurrence per subject (first. / last.)\n**Task.** For treatment-emergent AEs, keep each subject's earliest event (by ASTDT, then AESEQ). Then report the most severe AE per subject (MILD < MODERATE < SEVERE).\n\n**Solution.**\n```r\nfirst_ae <- adae |>\n  filter(TRTEMFL == \"Y\") |>\n  arrange(USUBJID, ASTDT, AESEQ) |>\n  group_by(USUBJID) |>\n  slice_head(n = 1) |>      # first.usubjid\n  ungroup()\n\nworst_ae <- adae |>\n  filter(TRTEMFL == \"Y\") |>\n  mutate(sevn = match(AESEV, c(\"MILD\", \"MODERATE\", \"SEVERE\"))) |>\n  group_by(USUBJID) |>\n  slice_max(sevn, n = 1, with_ties = FALSE) |>\n  ungroup()\n```\n**Point.** There is no `first.` or `last.`. Use `group_by` with `slice_head` / `slice_tail`, and remember to `ungroup()`.\n\n## Exercise 5: Overall AE summary table (the core of the daily work)\n**Task.** Build the standard TEAE overview. For each treatment arm, give n and % of safety-population subjects with: any TEAE, any serious TEAE, any TEAE with severity SEVERE. Denominators come from ADSL, not ADAE.\n\n**Solution.**\n```r\nbig_n <- adsl |> filter(SAFFL == \"Y\") |> count(TRT01A, name = \"N\")\n\nflag_summary <- function(df, label) {\n  df |>\n    distinct(USUBJID, TRT01A) |>\n    count(TRT01A, name = \"n\") |>\n    mutate(row = label)\n}\n\nteae <- adae |> filter(TRTEMFL == \"Y\", SAFFL == \"Y\")\n\noverview <- bind_rows(\n  flag_summary(teae, \"Any TEAE\"),\n  flag_summary(teae |> filter(AESER == \"Y\"), \"Any serious TEAE\"),\n  flag_summary(teae |> filter(AESEV == \"SEVERE\"), \"Any severe TEAE\")\n) |>\n  right_join(big_n, by = \"TRT01A\") |>\n  mutate(n = replace_na(n, 0L),\n         txt = sprintf(\"%d (%.1f%%)\", n, 100 * n / N)) |>\n  select(row, TRT01A, txt) |>\n  pivot_wider(names_from = TRT01A, values_from = txt)\n\noverview\n```\n**Points.**\n- Count unique subjects with `distinct(USUBJID)`, never raw record counts.\n- The denominator comes from ADSL. This is the most common AE table bug.\n- `pivot_wider` replaces `proc transpose`.\n- `sprintf` is `put` with a format.\n- Rounding: R's `round()` rounds half to even. `sprintf` is usually fine, but compare against your SAS output on borderline values.\n\n## Exercise 6: AE by SOC and preferred term (nested counts, sorted by frequency)\n**Task.** Produce the SOC / PT table: SOC rows with PT rows indented beneath. Show n (%) by arm plus Total. Sort SOCs and PTs by descending total frequency.\n\n**Solution.**\n```r\nadsl_s <- adsl |> filter(SAFFL == \"Y\") |> mutate(TRT = TRT01A)\nbig_n  <- bind_rows(adsl_s |> count(TRT, name = \"N\"),\n                    tibble(TRT = \"Total\", N = nrow(adsl_s)))\n\nteae <- adae |> filter(TRTEMFL == \"Y\") |>\n  semi_join(adsl_s, by = \"USUBJID\") |>\n  mutate(TRT = TRT01A)\nteae_tot <- bind_rows(teae, teae |> mutate(TRT = \"Total\"))\n\ncnt <- function(df, ...) {\n  df |> distinct(USUBJID, TRT, ...) |> count(TRT, ..., name = \"n\")\n}\n\nsoc <- cnt(teae_tot, AEBODSYS) |> mutate(AEDECOD = NA_character_, level = 1)\npt  <- cnt(teae_tot, AEBODSYS, AEDECOD) |> mutate(level = 2)\n\ntab <- bind_rows(soc, pt) |>\n  left_join(big_n, by = \"TRT\") |>\n  mutate(txt = sprintf(\"%d (%.1f%%)\", n, 100 * n / N))\n\n# sort keys: total frequency\nord <- tab |> filter(TRT == \"Total\") |>\n  select(AEBODSYS, AEDECOD, level, tot = n) |>\n  group_by(AEBODSYS) |>\n  mutate(soc_tot = tot[level == 1]) |>\n  ungroup()\n\nfinal <- tab |>\n  select(AEBODSYS, AEDECOD, level, TRT, txt) |>\n  pivot_wider(names_from = TRT, values_from = txt, values_fill = \"0\") |>\n  left_join(ord, by = c(\"AEBODSYS\", \"AEDECOD\", \"level\")) |>\n  arrange(desc(soc_tot), AEBODSYS, level, desc(tot), AEDECOD) |>\n  mutate(label = if_else(level == 1, AEBODSYS, paste0(\"   \", AEDECOD))) |>\n  select(label, everything(), -AEBODSYS, -AEDECOD, -level, -tot, -soc_tot)\n\nfinal\n```\n**Point.** The join key has NA for SOC rows. A join on `AEDECOD` still matches NA to NA in dplyr, but it is a common source of surprise. Tell them to test it.\n**Stretch.** Refactor into a function `ae_table(data, adsl, by = AESEV)`. Then discuss the packages your team may prefer: `gtsummary`, `tfrmt`, `rtables`/`tern` (the pharmaverse stack).\n\n## Exercise 7: Time-to-event (proc lifetest)\n**Task.** Using ADTTE, pick one PARAMCD (check with `count(adtte, PARAMCD, PARAM)`). Produce Kaplan-Meier medians by treatment, a log-rank p-value, and a Cox hazard ratio with 95% CI. Note CNSR = 1 means censored.\n\n**Solution.**\n```r\nadtte |> count(PARAMCD, PARAM)\n\nd <- adtte |>\n  filter(PARAMCD == \"TTDE\") |>        # change to a PARAMCD in your data\n  mutate(event = 1 - CNSR)            # R wants 1 = event; ADaM CNSR is reversed\n\nfit <- survfit(Surv(AVAL, event) ~ TRT01P, data = d)\nfit                                    # n, events, median, 95% CI\nsummary(fit, times = c(30, 60, 90))    # survival at timepoints\n\nsurvdiff(Surv(AVAL, event) ~ TRT01P, data = d)   # log-rank\n\ncox <- coxph(Surv(AVAL, event) ~ TRT01P, data = d, ties = \"efron\")\nsummary(cox)$conf.int\n```\n**Points.**\n- Flip CNSR to get the event indicator. This is the number one mistake.\n- Set the reference level with `relevel(factor(TRT01P), ref = \"Placebo\")`.\n- Match ties handling to SAS: SAS defaults to `ties=breslow`, R to `efron`. Use `ties = \"breslow\"` to reproduce SAS output.\n- Plot with `survminer::ggsurvplot(fit)` or `ggsurvfit`.\n\n## Exercise 8: QC against SAS (double programming)\n**Task.** Compare your R Exercise 5 output to a SAS-produced dataset. Report any differences.\n\n**Solution.**\n```r\nsas_out <- haven::read_sas(\"ae_overview_sas.sas7bdat\")\nwaldo::compare(as.data.frame(r_out), as.data.frame(sas_out))\n# or: all.equal(r_out, sas_out, check.attributes = FALSE)\n# or: diffdf::diffdf(r_out, sas_out, keys = \"row\")\n```\n**Point.** This mirrors proc compare. Differences usually come from:\n- Rounding.\n- Character versus numeric types.\n- Trailing blanks. SAS pads character values, so use `trimws()`.\n- Date origins. SAS dates count from 1960, R from 1970. `haven` converts for you.\n- Labels.\n\n---\n\n## Suggested pacing\nSpread these over about 4 short sessions:\n1. Exercises 1-2\n2. Exercises 3-4\n3. Exercises 5-6\n4. Exercises 7-8\n\nHave people work in RStudio or Posit Workbench. Pair a SAS expert with each learner for code review.\n\nIf you share the AE table program (or its spec/shell), I can tailor exercises 5 and 6 to match its exact layout, sort order, and footnotes, and add a SAS-versus-R side-by-side for each exercise.\n\n----------------------------------------------------------------------\nWHAT HAPPENS WHEN THIS IS CHECKED (added after the answer was saved; R 4.6.1, 2026-10-21). The data are the pilot xpt files.\n- Exercise 5 stops: Error in distinct(df, USUBJID, TRT01A): Must use existing variables. TRT01A not found in .data (ADAE has TRTA and TRTAN, not TRT01A).\n- Exercise 7 stops: object 'TRT01P' not found (ADTTE has TRTP, not TRT01P). PARAMCD \"TTDE\" does exist and the CNSR flip is right.\n- The setup uses the pharmaverseadam package datasets, not the supplied xpt files; the package is not in the project library.\n- Exercise 8 reads ae_overview_sas.sas7bdat, a file that does not exist.\n- The cheat sheet says \"NA > 5 returns NA, not TRUE as in SAS where missing sorts lowest\". In SAS a missing value is lower than any number, so . > 5 is FALSE.\n----------------------------------------------------------------------",
  "what_went_wrong": [
   "It never saw the program or the xpt files, said so (\"I haven't seen your AE table program\") and wrote a generic TEAE overview anyway; the real program counts serious events only and prints subjects, percent and events in brackets.",
   "It uses the pharmaverseadam package data and install.packages(), not the supplied xpt files. Confirmed by running code: the package is not in the project library.",
   "Exercise 5 uses TRT01A on ADAE. ADAE has TRTA and TRTAN. Run on the pilot data it stops: TRT01A not found in .data.",
   "Exercise 7 uses TRT01P on ADTTE, which has TRTP. Run on the pilot data it stops: object TRT01P not found.",
   "Its cheat sheet says NA > 5 returns NA, not TRUE as in SAS where missing sorts lowest. In SAS a missing value is lower than any number, so . > 5 is FALSE. The actual trap (the >.z tests in adam_adae.sas) is not mentioned.",
   "Exercise 8 reads ae_overview_sas.sas7bdat, a file that does not exist, and offers no check value anywhere. It says it did not run the code.",
   "No exercise is tied to the real SAS code, to a check against adam_adae.xpt, or to the CSR tables, and no team tasks or list of unknowns were produced."
  ]
 },
 "what_changed": [
  "Input: the lazy request became the real SAS statements, the real file and column names, and a labelled (invented) list of team tasks, so the exercises could name the statement each one replaces.",
  "Output: a generic course outline using other data became six exercises that each name the SAS lines they map to, give a hint, a runnable solution, a CHECK line and the SAS-versus-R differences.",
  "The prompt forbade numbers the model could not know (\"compare with ...\"), so no result is stated without a source. The check then came from running the code, not from the model.",
  "Running every solution is what found the one real problem: Exercise 5 ran without an error and printed p = 1 twice. A reader who only reads the code would not see it.",
  "The model listed what it could not know (merge-back of flags, ADURN, treatment codes); two of those items were answered by the full SAS files, one by the data."
 ],
 "check_before_trust": [
  "Run every model solution yourself, unedited, from the folder holding the xpt files, and keep the console output. A solution that runs without an error can still be wrong (Exercise 5 gave p = 1 twice).",
  "Print the values of the treatment variables before you filter on them. Here TRTAN is 0, 54 and 81 in the data; the SAS program and the model both use 0, 1 and 2.",
  "Compare with a number from outside the code: the CSR table (Tables 14-5.01 and 14-5.02 here), not only a flag stored in the same dataset. Checks against AOCC flags in adam_adae.xpt confirm the macro logic but are partly circular.",
  "Do not trust a statement about SAS behaviour that was not run in SAS. Several in this answer (Fisher tolerance, empty proc freq column, length of a blank) were checked against documentation only, and one tolerance claim has no source.",
  "Check for things the exercise hides: a forced 2 by 2 table turned the wrong codes into a clean-looking p = 1 instead of an error.",
  "Contamination: the CDISC pilot programs and data are public and may be familiar to the model. One model, one run each: this shows what happened once, not how often."
 ],
 "model_could_not_know": [
  "The real values of the treatment codes (0, 54, 81).",
  "How the seven flag datasets are merged back and how unflagged rows are stored (in the full adam_adae.sas, not in the excerpt).",
  "How ADURN and ADURU are derived (the program has ADUR; the xpt has ADURN and ADURU).",
  "The CSR counts and p-values the table program should reproduce (CSR pages 63 and 79).",
  "Which exercises the team really needs (the team tasks here are invented).",
  "The SAS version, locale and options in setup.sas (not in the repository)."
 ],
 "verification": {
  "answer_key": "Recomputed. Reference: the SAS-produced adam_adae.xpt (1191 rows) and CSR Tables 14-5.01 (PDF p.63) and 14-5.02 (PDF p.79), with the numbers recomputed by separate R and Python scripts saved with the page. SAS behaviour claims could not be run (no SAS available) and are marked partly or not in source where that applies.",
  "rows": [
   {
    "claim": "Row counts AE 1191, ADSL 254, ADAE 1191",
    "verdict": "correct",
    "cite": "good_input lines 4-6; v.R"
   },
   {
    "claim": "TRTAN 0 = placebo, 1 = low, 2 = high",
    "verdict": "wrong",
    "cite": "v.R: codes are 0/54/81"
   },
   {
    "claim": "Code not run; no numbers stated except the three row counts",
    "verdict": "correct",
    "cite": "whole output"
   },
   {
    "claim": "Ex1 duplicate/orphan key counts all 0",
    "verdict": "correct",
    "cite": "ex1_output.txt"
   },
   {
    "claim": "Ex1 four ADAE date columns are class Date",
    "verdict": "correct",
    "cite": "ex1_output.txt"
   },
   {
    "claim": "Blank SAS character arrives as \"\", test both",
    "verdict": "correct",
    "cite": "ex1: AEENDTC 473, AEACN 1191 blank"
   },
   {
    "claim": "7-character AESTDTC are month-only dates",
    "verdict": "correct",
    "cite": "15 rows, all imputed (ASTDTF = D, 15)"
   },
   {
    "claim": "The `??` modifier \"handles blank texts\"",
    "verdict": "partly",
    "cite": "`??` only suppresses invalid-data messages (adam_adae.sas line 13); the result is missing, not handled"
   },
   {
    "claim": "dplyr 1.1.0+ `arrange()` uses C locale, base `order()` uses locale",
    "verdict": "correct",
    "cite": "b.R: arrange gives A a b; order gives a A b"
   },
   {
    "claim": "SAS sorts missing first and text \"in its collating sequence\"",
    "verdict": "partly",
    "cite": "missing first is right; collating sequence is ASCII on Windows/Unix and EBCDIC on mainframe, not stated; not run"
   },
   {
    "claim": "haven converts 1960-origin dates to Date",
    "verdict": "correct",
    "cite": "Ex1 class Date; Ex2/3 dates match ADAE"
   },
   {
    "claim": "SAS yymmdd10. reads exactly 10 chars; `str_sub(,1,10)` imitates it",
    "verdict": "partly",
    "cite": "Ex2 zero mismatches support it; SAS behaviour on 7-char text with trailing blanks not run"
   },
   {
    "claim": "`as.Date(format=)` ignores trailing characters",
    "verdict": "correct",
    "cite": "b.R: \"2014-01-02T10:00\" gives 2014-01-02"
   },
   {
    "claim": "`Date - Date` is difftime; wrap in as.numeric",
    "verdict": "correct",
    "cite": "standard R; Ex2 runs"
   },
   {
    "claim": "Ex2 AENDT and ASTDT mismatches equal 0",
    "verdict": "correct",
    "cite": "ex2_output.txt"
   },
   {
    "claim": "Ex2 rows missing here but present in ADAE are month-only, length 7 only",
    "verdict": "correct",
    "cite": "15 rows, all length 7"
   },
   {
    "claim": "ADAE has no ADUR, only ADURN/ADURU; their derivation is not in the text",
    "verdict": "correct",
    "cite": "xpt columns; adam_adae.sas has only ADUR (lines 15, 125, 131); xcheck_output.txt"
   },
   {
    "claim": "ADUR vs ADURN differences \"may come from imputed start dates\"",
    "verdict": "partly",
    "cite": "speculation; actual mismatches 0"
   },
   {
    "claim": "Ex3 all 18 mismatch counts should be 0",
    "verdict": "correct",
    "cite": "ex3_output.txt (all 0)"
   },
   {
    "claim": "In SAS missing is lower than any number, hence the `>.z`",
    "verdict": "correct",
    "cite": "adam_adae.sas lines 33-41"
   },
   {
    "claim": "In R a comparison with NA is NA, test with is.na",
    "verdict": "correct",
    "cite": "b.R; Ex3 runs"
   },
   {
    "claim": "`if_else` gives NA for an NA condition; `case_when` treats NA as not matched",
    "verdict": "correct",
    "cite": "b.R: if_else(NA,1,2) = NA; case_when(NA ~ 1, .default = 9) = 9"
   },
   {
    "claim": "SAS `length()` of a blank returns 1; no effect on `= 7`",
    "verdict": "correct",
    "cite": "documented SAS behaviour, not run; logic of line 28 holds"
   },
   {
    "claim": "Duplicate ADSL USUBJID: \"SAS would repeat the values\" while left_join multiplies AE rows",
    "verdict": "partly",
    "cite": "SAS match-merge does not form a Cartesian product; ambiguous sentence; not run"
   },
   {
    "claim": "`length CQ01NAM $25` fixes text length",
    "verdict": "correct",
    "cite": "adam_adae.sas line 32"
   },
   {
    "claim": "ANLSTDY is derived but not in ADAE",
    "verdict": "correct",
    "cite": "line 37; commented out in the keep list (line 130); not in xpt"
   },
   {
    "claim": "`put(x,8.1)` rounds half away from zero; `round(0.25,1)` is 0.2",
    "verdict": "correct",
    "cite": "b.R: round 0.2, sprintf 0.2 for 0.25"
   },
   {
    "claim": "`best.` has no R equivalent; `%d` gives same text",
    "verdict": "correct",
    "cite": "Ex4 RESULT strings"
   },
   {
    "claim": "SQL `count()` ignores NULL, `n()` counts rows",
    "verdict": "correct",
    "cite": "standard; no blank USUBJID in data"
   },
   {
    "claim": "Ex4 count equals AOCC04FL cell count, last line prints 0",
    "verdict": "correct",
    "cite": "ex4_output.txt \"0\" (circular, see Caveats)"
   },
   {
    "claim": "Denominator total cannot exceed 254",
    "verdict": "correct",
    "cite": "actual total is exactly 254 (86+84+84)"
   },
   {
    "claim": "In the SAS join STUDYID comes from the right table and is non-missing only for event subjects",
    "verdict": "correct",
    "cite": "adam_at14-5-02.sas FISHER2 step (BACKBONE2 has no STUDYID)"
   },
   {
    "claim": "Ex5 p-values \"must equal SAS F1SUB/F2SUB\"",
    "verdict": "partly",
    "cite": "principle right; as coded R gives p = 1 and 1, and SAS itself selects no active subjects; correct values 0.243 (high) and 0.494 (low)"
   },
   {
    "claim": "Factor levels keep a 2x2 table and fisher.test then gives p = 1",
    "verdict": "correct",
    "cite": "ex5_output.txt; b.R; it also hides the code error"
   },
   {
    "claim": "`fisher.test` uses relative tolerance 1e-7 \"as SAS does\"",
    "verdict": "not in source",
    "cite": "R side plausible; SAS tolerance is in no supplied file"
   },
   {
    "claim": "fisher.test also returns a conditional odds ratio",
    "verdict": "correct",
    "cite": "R documentation"
   },
   {
    "claim": "Name1 `XP2_FISH` is likely the two-sided p-value",
    "verdict": "correct",
    "cite": "R two-sided p equals CSR p 0.494 / 0.243 (Table 14-5.02)"
   },
   {
    "claim": "Ex5 `sum(EVENT)` per arm equals AOCC02FL count",
    "verdict": "correct",
    "cite": "0 / 1 / 2 vs 1 / 2 (placebo row absent from second table)"
   },
   {
    "claim": "proc freq drops an empty column and gives a 1-column table",
    "verdict": "partly",
    "cite": "plausible SAS behaviour; not run"
   },
   {
    "claim": "Ex6 all 8 mismatch counts equal 0",
    "verdict": "correct",
    "cite": "ex6_output.txt; non-blank counts 493, 218, 550, 781, 3, 3, 3, 152"
   },
   {
    "claim": "SAS `index()` of blank is 0; `str_detect(\"\")` FALSE, NA gives NA",
    "verdict": "correct",
    "cite": "b.R"
   },
   {
    "claim": "SAS ignores trailing blanks in comparison, R does not",
    "verdict": "correct",
    "cite": "standard SAS behaviour"
   },
   {
    "claim": "`%in%` never returns NA but `==` can",
    "verdict": "correct",
    "cite": "standard R"
   },
   {
    "claim": "\"Order within the groups does not matter ... ties resolved by ASTDT, AESEQ\"",
    "verdict": "partly",
    "cite": "garbled: ASTDT order decides the kept row; AESEQ ties match proc sort stability; result matches (0 mismatches)"
   },
   {
    "claim": "Unflagged rows in ADAE are blank, not \"N\"",
    "verdict": "correct",
    "cite": "AOCC02FL \"\" 1188, Y 3"
   },
   {
    "claim": "`%if &invar ne %then and &invar ne ''` is a no-op filter when invar is empty",
    "verdict": "correct",
    "cite": "adam_adae.sas lines 57-61; zero mismatches"
   },
   {
    "claim": "Gap 2: merge-back of the seven flag datasets is not in the text",
    "verdict": "false gap",
    "cite": "true for the excerpt only; `merge AE AEA AEB AEC SAEA SAEB SAEC DERM; by usubjid aeseq;` is in adam_adae.sas lines 91-96"
   },
   {
    "claim": "Gap 8: SOC-level and subject-level count blocks left out",
    "verdict": "false gap",
    "cite": "omitted from the excerpt only; present in adam_at14-5-02.sas"
   },
   {
    "claim": "Gaps 1 and 9 (date lengths, key uniqueness) cannot be told from the text",
    "verdict": "correct",
    "cite": "now answered: lengths 4/7/10; keys unique (Ex1 zeros)"
   },
   {
    "claim": "Gaps 5 and 7 (numeric results, TRTAN labels) are unknown",
    "verdict": "correct",
    "cite": "genuine gap, resolvable from the data and CSR pages 63/79"
   },
   {
    "claim": "Gaps 3, 4, 6, 11, 12 (hidden code, ADURN, XP2_FISH, setup.sas, ADTTE unused)",
    "verdict": "correct",
    "cite": "none contradicted"
   }
  ],
  "errors_found": [
   "Treatment codes: the model inferred TRTAN 0 = placebo, 1 = low, 2 = high from the program comments and hard-coded 0/1/2 in Exercise 5. The data hold 0, 54 and 81, so the Fisher step ran on empty active arms and returned p = 1 for both comparisons. The model had flagged the inference as unconfirmed, but the code still shipped with it.",
   "The SAS program itself has the same stale filters (TRTAN in (0,2) and (0,1)); on the shipped ADSL they match only the 86 placebo subjects, so the published Fisher p-values cannot be regenerated by running that program on these data. The model inherited the error from the source.",
   "Weak statements in the model text: the ?? modifier \"handles\" blanks (it only hides messages); the ADUR versus ADURN differences \"may come from imputed start dates\" (actual mismatches 0); an unclear sentence on duplicate keys in a SAS merge; a garbled sentence on tie order; and a claim that SAS and R Fisher tolerances match, which no supplied source supports.",
   "Two gap-list items (merge-back of the seven flag datasets; the SOC-level and subject-level blocks) are answered in the full SAS files; they were gaps only in the shortened excerpt.",
   "Helper weakness: sas_round adds a 1e-9 fudge; no percentage in this data is a half case, so no output is affected."
  ],
  "summary": "51 claims checked by an independent verifier (a separate subagent that did not write the output): 39 correct, 8 partly, 1 wrong, 1 not in source, 2 false gap. All six solutions ran unedited in R 4.6.1. Exercises 1, 2, 3, 4 and 6 passed every check (0 mismatches against adam_adae.xpt; serious and any treatment-emergent AE counts equal CSR Tables 14-5.02 and 14-5.01). Exercise 5 ran but failed as written (p = 1 twice) because of the treatment codes; with 54 and 81 it gives p = 0.243 (high) and 0.494 (low), equal to the CSR. The bad output has seven checked faults, three of them confirmed by running its code. No time-saved or regulatory-acceptance claim is made. See VERIFICATION_REPORT_r-training-exercises-for-sas-programmers.md."
 },
 "run": {
  "generated_by": "Claude (Anthropic), run as a subagent on 2026-10-21 (cold answer from the input excerpt and prompt only; the lazy answer from the lazy request only). Solutions run in R 4.6.1 (haven 2.5.5, dplyr 1.2.1, stringr 1.6.0, tidyr, tibble 3.3.1) on 2026-10-21. Verified by a separate subagent. Independence caveat: the builder who ran the code and the verifier are the same model family.",
  "not_tested_in": "Microsoft 365 Copilot"
 },
 "run_summary": [
  {
   "kind": "fail",
   "label": "Exercise 5 as written",
   "text": "Ran without error but returned p = 1 twice. TRTAN is 0, 54, 81 in the data; the model (and the SAS program) use 0, 1, 2."
  },
  {
   "kind": "warn",
   "label": "One fix",
   "text": "c(0, 2) to c(0, 81) and c(0, 1) to c(0, 54): p = 0.243 and 0.494, equal to CSR Table 14-5.02."
  },
  {
   "kind": "ok",
   "label": "Other five",
   "text": "Ran first time. 0 mismatches against adam_adae.xpt; TEAE counts 65/77/76 and serious 0/1/2 equal CSR Tables 14-5.01 and 14-5.02."
  }
 ]
}