A tour of clinical R
You learn R by writing R programs. This chapter is a fast tour: six small programs that use the R you need most in a clinical trial. Do not try to understand every detail now. Each later chapter explains one part in full.
All programs use the same study: the CDISC pilot study, a real Alzheimer’s disease trial that was made public for teaching. It has 254 randomised subjects in three arms: placebo, a low dose and a high dose of the drug xanomeline.
1.1 A first program
Section titled “1.1 A first program”A program is a text file of instructions. R reads it from top to bottom and does each instruction in turn. Here is the first one, with its output. Lines that start with #> are what R printed. Everything else is the program.
# Chapter 1: a first program. Read ADSL, keep five columns, count the subjects per armlibrary(dplyr)
adsl <- pharmaverseadam::adsl |> select(USUBJID, ARM, AGE, SEX, SAFFL)
adsl |> count(ARM)#> # A tibble: 4 x 2#> ARM n#> <chr> <int>#> 1 Placebo 86#> 2 Screen Failure 52#> 3 Xanomeline High Dose 84#> 4 Xanomeline Low Dose 84Read it line by line:
- A line that starts with
#is a comment. R ignores it. It is a note for the person who reads the program. library(dplyr)loads a package: a set of functions that someone wrote and shared.dplyris the package for working with tables of data. You load it once at the top of a program.pharmaverseadam::adslis a table of data that thepharmaverseadampackage gives you.::means “from this package”. In R, a table of data is a data frame: rows (here, one per subject) and named columns (USUBJID,ARM,AGE, …).|>is the pipe. Read it as “and then”. It gives the result of one step to the next step.select()keeps only the columns that you name.count()counts the rows for each value of a column.adsl <- ...stores the result under the nameadsl.<-is the assignment arrow. Read it as “gets”.
The output is a tibble, the tidyverse name for a data frame. It has 4 rows: the three arms and a fourth group, Screen Failure, with 52 subjects. These people signed consent but were never randomised. You will remove them in the next program.
Exercise 1-1. Change count(ARM) to count(SEX), and add filter(SAFFL == "Y") |> before it, as program 01_2 does. How many women and men are in the study?
1.2 Make a new column
Section titled “1.2 Make a new column”# Chapter 1: if_else() makes a new column from an old onelibrary(dplyr)
adsl_age <- pharmaverseadam::adsl |> filter(SAFFL == "Y") |> select(USUBJID, ARM, AGE) |> mutate(AGEGRP = if_else(AGE >= 65, "65 or older", "under 65"))
adsl_age |> count(AGEGRP)#> # A tibble: 2 x 2#> AGEGRP n#> <chr> <int>#> 1 65 or older 221#> 2 under 65 33filter()keeps the rows where a condition is true.SAFFL == "Y"is true for the subjects in the safety population: the 254 who were randomised and took the drug.==asks “is equal to?”. One=would be an error here.mutate()makes a new column, or changes one. Here the new column isAGEGRP.if_else(condition, yes, no)gives one value when the condition is true and another when it is false. It works on the whole column at once: 254 answers, one per row.
Of the 254 subjects, 221 are 65 or older and 33 are under 65.
Exercise 1-2. Change the program so that it counts the subjects older than 80. How many are there?
1.3 Sort, then work in groups
Section titled “1.3 Sort, then work in groups”# Chapter 1: sort, then work in groups. The oldest subject of each armlibrary(dplyr)
pharmaverseadam::adsl |> filter(SAFFL == "Y") |> select(USUBJID, ARM, AGE) |> arrange(ARM, desc(AGE), USUBJID) |> group_by(ARM) |> slice_head(n = 1) |> ungroup()#> # A tibble: 3 x 3#> USUBJID ARM AGE#> <chr> <chr> <dbl>#> 1 01-710-1083 Placebo 89#> 2 01-703-1295 Xanomeline High Dose 88#> 3 01-710-1002 Xanomeline Low Dose 88What you see: the oldest subject of each arm.
arrange()sorts the rows: by arm, then within an arm from the oldest down (desc()means descending).USUBJIDbreaks a tie, so the result is the same every time.group_by(ARM)tells the next steps to work on each arm separately.slice_head(n = 1)keeps the first row of each group.ungroup()removes the groups again, so that later steps see the whole table.
Chapter 4 explains groups step by step.
Exercise 1-3. Remove desc() and keep AGE. What do you get now?
1.4 Summary statistics
Section titled “1.4 Summary statistics”# Chapter 1: summary statistics per armlibrary(dplyr)
pharmaverseadam::adsl |> filter(SAFFL == "Y") |> group_by(ARM) |> summarise( n = n(), mean = round(mean(AGE), 1), sd = round(sd(AGE), 1), min = min(AGE), max = max(AGE) )#> # A tibble: 3 x 6#> ARM n mean sd min max#> <chr> <int> <dbl> <dbl> <dbl> <dbl>#> 1 Placebo 86 75.2 8.6 52 89#> 2 Xanomeline High Dose 84 74.4 7.9 56 88#> 3 Xanomeline Low Dose 84 75.7 8.3 51 88summarise() turns each group into one row. Each line inside it makes one column of the result: n() counts the rows, mean() and sd() give the mean and the standard deviation, round(x, 1) keeps one decimal. These are the numbers of the age rows in a demographics table (chapter 13).
1.5 Count subjects, not records
Section titled “1.5 Count subjects, not records”# Chapter 1: count subjects, not recordslibrary(dplyr)
pharmaverseadam::adae |> filter(TRTEMFL == "Y") |> group_by(TRT01A) |> summarise( records = n(), subjects = n_distinct(USUBJID) )#> # A tibble: 3 x 3#> TRT01A records subjects#> <chr> <int> <int>#> 1 Placebo 281 65#> 2 Xanomeline High Dose 414 68#> 3 Xanomeline Low Dose 427 84ADAE holds the adverse events: one row per event, not one row per subject. A subject can have many events. n() counts rows (events). n_distinct(USUBJID) counts each subject once.
A safety table reports subjects: 65 subjects on placebo had at least one treatment-emergent adverse event (TRTEMFL == "Y": an event that started or got worse after the first dose). They had 281 such events between them. If you report 281 as the number of subjects, the table is wrong. This is the most important rule of clinical tables.
Exercise 1-4. Add AESEV == "SEVERE" inside the filter(), after a comma. How many subjects per arm had a severe event?
1.6 Write a value once
Section titled “1.6 Write a value once”# Chapter 1: write a value once, in a variable, and use it many timeslibrary(dplyr)
arm <- "Placebo"
pharmaverseadam::adsl |> filter(SAFFL == "Y", ARM == arm) |> summarise( arm = arm, n = n(), mean = round(mean(AGE), 1), min = min(AGE), max = max(AGE) )#> # A tibble: 1 x 5#> arm n mean min max#> <chr> <int> <dbl> <dbl> <dbl>#> 1 Placebo 86 75.2 52 89arm <- "Placebo" stores a text value in a variable called arm. The program uses it twice: in the filter() and in the result. To look at another arm, you change one line. A value that you write in only one place cannot disagree with itself.
Exercise 1-5. Change the value to "Xanomeline Low Dose". What are n, the mean and the oldest age?
1.7 What you have seen
Section titled “1.7 What you have seen”| Program | Idea | Explained in |
|---|---|---|
| 01_1 | packages, data frames, the pipe, select(), count() |
Chapter 2 |
| 01_2 | filter(), mutate(), if_else() |
Chapter 2, chapter 3 |
| 01_3 | arrange(), group_by(), slice_head() |
Chapter 4 |
| 01_4 | summarise(), mean(), sd() |
Chapter 6 |
| 01_5 | n() and n_distinct(): records and subjects |
Chapter 6 |
| 01_6 | a variable that holds a value | Chapter 8 |
That is most of the R in a clinical study: about ten functions from one package. The rest of this chapter shows where the data comes from and what the numbers are for.
1.8 The work of a clinical programmer
Section titled “1.8 The work of a clinical programmer”A clinical programmer turns trial data into the numbers that a regulator reads, such as the US Food and Drug Administration (FDA). Two rules shape every page of this book:
- Every number must be traceable to the data it came from.
- A second programmer must be able to reproduce it.
1.9 The documents that drive your work
Section titled “1.9 The documents that drive your work”You do not decide what to compute. Documents decide it. You implement them exactly.
| Document | Written by | What you take from it |
|---|---|---|
| Protocol | Clinical team | Visits, treatments, populations, the primary endpoint |
| Statistical analysis plan (SAP) | Statistician | Populations, derivation rules, imputation rules, models |
| TLF shells (mock tables) | Statistician | The layout of each output: rows, columns, decimals, footnotes |
| ADaM specification | Lead programmer | Every ADaM variable: name, label, type, derivation |
| define.xml | Programmer (generated) | The metadata sent to the regulator with the data |
TLF means tables, listings and figures. When two documents disagree, do not choose. Ask the statistician, and write the answer where the next programmer can find it.
1.10 SDTM and ADaM
Section titled “1.10 SDTM and ADaM”The study data comes in two standards of CDISC (the Clinical Data Interchange Standards Consortium). SDTM holds what was collected. ADaM holds what the analysis needs.
| SDTM | ADaM | |
|---|---|---|
| Purpose | Show what was collected | Make the analysis easy |
| Organised by | Topic: DM, AE, LB, VS, EX, DS | Analysis need: ADSL, ADAE, ADLB, ADTTE |
| Dates | ISO 8601 text, can be partial: 2014-03 |
Real dates (ADT), with imputation flags |
| Derived values | Few | Many: baseline, change, flags, analysis visits |
| In this book | pharmaversesdtm::dm, ::ae, … |
you build them; pharmaverseadam is the reference |
The core ADaM rule is “one step away”. A table program only selects rows with flags, counts, summarises and prints. If a table program must derive a value, that value belongs in ADaM.
ADaM has four structures:
- ADSL, subject level: one row per subject. Treatment, populations, demography, key dates. Chapter 9.
- BDS, basic data structure: one row per subject, parameter and time point. Labs, vital signs. Chapter 10.
- OCCDS, occurrence data: one row per event. Adverse events, medications. Chapter 11.
- ADTTE, time to event: a BDS with the time (
AVAL) and a censor flag (CNSR). Chapter 12.
1.11 One number, traced
Section titled “1.11 One number, traced”SDTM DM of the pilot study holds 306 subjects. 52 are screen failures: they signed consent, but they were never randomised. The safety population keeps the 254 randomised subjects: 86 on placebo, 84 on the low dose, 84 on the high dose. Program 01_1 counted them.
When a table says N = 86, you must be able to show the 86 rows that made it. That is traceability. In R, the rows are one filter() away: filter(SAFFL == "Y", ARM == "Placebo").
1.12 Why every number is built twice
Section titled “1.12 Why every number is built twice”The usual standard is double programming. Two programmers write the same specification independently. Then a compare tool must find no differences (chapter 15 uses diffdf).
This changes how you write code. Your program must:
- be easy to read for the second programmer,
- give the same result each time it runs,
- run without unexplained warnings.
A program that is right but cannot be checked is not finished.
1.13 Exercises
Section titled “1.13 Exercises”Exercises 1-1 to 1-5 are in the sections above. Three more:
Exercise 1-6. Name the SDTM domain and variable that hold the date of the first study treatment. Name the ADSL variable that holds it as a real date.
Exercise 1-7. A table program computes “change from baseline” itself. Which ADaM rule does it break?
Exercise 1-8. DM has 306 rows and the safety population has 254 subjects. Write one sentence for a reviewer that explains the difference.
The answers are in Answers, Part I.
Found an error or have a question? Write to datastep.studio@gmail.com· Every program runs in DataStep Studio for R, the R extension for VS Code and Positron.
Data: the CDISC pilot study (cdiscpilot01), from the R packagespharmaversesdtm andpharmaverseadam (Apache License 2.0).
R is a project of the R Foundation. SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. This book is not affiliated with or endorsed by SAS Institute Inc. or the R Foundation. CDISC, SDTM and ADaM are trademarks of the Clinical Data Interchange Standards Consortium.
© 2026 DataStep Labs. All rights reserved.