Six R exercises for SAS programmers, with solutions that run
Paste a SAS program, get six R exercises with solutions. All six were run; one is wrong and labelled.
About 45 minWord and RWorked example, recomputed
What you get
Six exercises on the CDISC pilot data. Team tasks T1 to T4 are invented. Every model solution was run in R 4.6.1.
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.
Replaces: sdtmnew.AE / adamnew.ADSL libname access, and proc sort data=sdtmnew.AE out=AE; by USUBJID AESEQ;
Hint. read_xpt() returns a tibble. A blank SAS character value arrives as "", not NA, so test for both.
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.
Replaces: ASTDT=input(strip(AESTDTC),?? yymmdd10.); AENDT=...; if ASTDT>.z and AENDT>.z then ADUR=AENDT-ASTDT+1; format ... DATE9.;
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().
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.
Replaces: 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.
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.
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.
Replaces: The proc sql blocks DENOM, AEPTD, AEPTA and RESULTPT (count(distinct usubjid), count(usubjid), left join, put(..., 8.1)).
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.
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.
Replaces: BACKBONE2, HADEVENT2, FISHER2 (the left join and case when STUDYID=...) and the two proc freq ... table TRTAN*EVENT/exact; steps with ods output FishersExact=....
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.
KNOWN ERROR, left in on purpose. The model solution hard-codes treatment codes 0, 1, 2; the data hold 0, 54, 81. It runs and returns p = 1 twice. Fixed file: p = 0.243 and 0.494.
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).
Replaces: The IF index(aedecod,...) ... then CQ01NAM='DERMATOLOGIC EVENTS' statement, the whole %macro flagfrst ... %mend and its seven calls.
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.
Swipe sideways to see every column.
Learner view of the worksheet (task, SAS statement, hint). The download adds checks and instructor notes.
Draft for review. Public data only.
The prompt
Write six R exercises for SAS programmers from the SAS program below, easiest to hardest.
Each: task (one paragraph), the SAS statement it replaces, one hint, a complete runnable solution
(haven, dplyr, tidyr, stringr), and a CHECK saying what the result must equal in the dataset.
Name every place where SAS and R behave differently.
State no number you cannot get from the text; write "compare with ..." instead.
End with what you could not tell from the text.
[paste the SAS program, file notes and your team tasks here]Works in any chat assistant that writes R; not tested in Microsoft 365 Copilot
Sample input used here
SAS programs adam_adae.sas and adam_at14-5-02.sas (start shown), CDISCPILOT01
=== adam_adae.sas (part 1; blank lines and whole-line comments removed) === proc sort data=sdtmnew.AE OUT=AE; by USUBJID AESEQ; run; data AE; set AE; by USUBJID AESEQ; ASTDT=input(strip(AESTDTC),?? yymmdd10.); AENDT=input(strip(AEENDTC),?? yymmdd10.); if ASTDT>.z and AENDT>.z then ADUR=AENDT-ASTDT+1; format ASTDT AENDT DATE9.; run; proc sort data=adamnew.ADSL OUT=TEMP(keep=SITEID USUBJID TRT01A TRT01AN AGE AGEGR1 AGEGR1N RACE RACEN SEX SAFFL
CDISC pilot programs, credited to CDISC. The team tasks T1 to T4 in the full paste are INVENTED.
How this was checked
Result
Generated by Claude on 2026-10-21; solutions run in R 4.6.1 on 2026-10-21 and re-run 2026-10-24.
Worked example, recomputed. A script recomputed the values from the data and they matched or were flagged. Statements a script cannot test were checked by a second Claude agent.
Prompt shortened for this page. The output shown came from the earlier run of the longer prompt (2026-10-21).
Re-check on 2026-10-24. All published solution scripts and the reference script re-run with R 4.6.1: output identical to the saved run (Exercise 5 as written still gives p = 1 twice; the fixed file gives 0.243 and 0.494). Code only: the AI was not re-run.
The longer prompt that was checked
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: 1. Task: the text the learner sees, one paragraph. 2. SAS maps to: the SAS statement(s) it replaces. 3. Hint: one. 4. Model solution: complete R code (haven, dplyr, tidyr, stringr), runnable as written when the xpt files are in the working directory. 5. CHECK: what the solution's result must equal (a column or count in adam_adae.xpt, or a result the table program would give). 6. Team task: T1 to T4, or none. Rules: 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.
A one-line prompt for comparison
Prompt: 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.
# R Exercises for SAS Programmers (CDISC Pilot: ADSL, ADAE, ADTTE)
**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:
- Population and treatment: SAFFL, TRT01A, TRT01P
- Adverse events: TRTEMFL, AEBODSYS, AEDECOD, AESEV, AESER
- Time to event: PARAMCD, AVAL, CNSR
I haven't run any of this code. Please run it once before handing it out and fix any names that differ in your copy.
Setup for all exercises:
```r
install.packages(c("tidyverse", "haven", "pharmaverseadam", "survival", "gt"))
library(tidyverse)
library(haven)
...About the sheet shown
Learner view of the worksheet (task, SAS statement, hint). The download adds checks and instructor notes. Generated by Claude on 2026-10-21.
All 5 checks
- Do not trust statements about SAS behaviour that were not run in SAS. Several here were checked against documentation only.
- Look 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.
Sources
- CDISC SDTM/ADaM pilot project (CDISC terms of use; used unmodified, not redistributed)
Scripts
- Reference counts from the data (not AI code)
- Licence (MIT)
- Expected console output: ex1_solution_as_written_output.txt
- Expected console output: ex2_solution_as_written_output.txt
- Expected console output: ex3_solution_as_written_output.txt
- Expected console output: ex4_solution_as_written_output.txt
- Expected console output: ex5_fixed_TRTAN_54_81_output.txt
- Expected console output: ex5_solution_as_written_output.txt
- Expected console output: ex6_solution_as_written_output.txt
- Expected console output: recompute_reference_output.txt
- Full input used here
- Record of the earlier run (JSON; the page above reflects the newer check)
- Scripts to rerun this check
Related workflows
All workflows. How we check. Public data only. Drafts for review, not validated output.
Get one workflow a week
Unsubscribe anytime. Privacy.