Answers, Part I (chapters 5 to 8)
Each answer gives the result first, then the program that produced it. Try the exercise yourself before you read the answer.
Chapter 5
Section titled “Chapter 5”Back to chapter 5, combining data.
Exercise 5-1
Section titled “Exercise 5-1”You get the three AE rows of S2 and S4: HEADACHE, DIZZINESS and NAUSEA. A semi join keeps the rows of the first table that have a partner. Now the first table is ae, and S4 has two rows in it, so both stay. A semi join never adds a row: each row of ae comes at most once. RASH of S5 has no partner in dm, so it is dropped.
# Exercise 5-1: semi_join() with AE first keeps AE rows, and never repeats themlibrary(dplyr)
dm <- tibble(USUBJID = c("S1", "S2", "S3", "S4"), AGE = c(63, 64, 71, 74))ae <- tibble( USUBJID = c("S2", "S4", "S4", "S5"), AEDECOD = c("HEADACHE", "DIZZINESS", "NAUSEA", "RASH"))
semi_join(ae, dm, by = join_by(USUBJID))#> # A tibble: 3 x 2#> USUBJID AEDECOD#> <chr> <chr>#> 1 S2 HEADACHE#> 2 S4 DIZZINESS#> 3 S4 NAUSEAExercise 5-2
Section titled “Exercise 5-2”29 subjects of the safety population have no record in ADAE: 17 on placebo, 2 on the high dose and 10 on the low dose. anti_join() keeps the ADSL rows without a partner in ADAE.
# Exercise 5-2: subjects of the safety population with no record in ADAElibrary(dplyr)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")adae <- pharmaverseadam::adae
no_ae <- anti_join(adsl, adae, by = join_by(USUBJID))nrow(no_ae)#> [1] 29no_ae |> count(TRT01A)#> # A tibble: 3 x 2#> TRT01A n#> <chr> <int>#> 1 Placebo 17#> 2 Xanomeline High Dose 2#> 3 Xanomeline Low Dose 10Exercise 5-3
Section titled “Exercise 5-3”3 rows come from AE and 66 from CM, 69 in all. select() renames the columns as it keeps them (TERM = AEDECOD), so that both tables have the same names before the stack. Sorted by START, the medications come first: some of them started in 2003, years before the study.
# Exercise 5-3: stack the AE and CM records of one subject into one tablelibrary(dplyr)
ae <- pharmaversesdtm::ae |> filter(USUBJID == "01-701-1015") |> select(USUBJID, TERM = AEDECOD, START = AESTDTC)cm <- pharmaversesdtm::cm |> filter(USUBJID == "01-701-1015") |> select(USUBJID, TERM = CMDECOD, START = CMSTDTC)
events <- bind_rows(AE = ae, CM = cm, .id = "DOMAIN")events |> count(DOMAIN)#> # A tibble: 2 x 2#> DOMAIN n#> <chr> <int>#> 1 AE 3#> 2 CM 66events |> arrange(START) |> print(n = 3)#> # A tibble: 69 x 4#> DOMAIN USUBJID TERM START#> <chr> <chr> <chr> <chr>#> 1 CM 01-701-1015 ACETYLSALICYLIC ACID 2003#> 2 CM 01-701-1015 ACETYLSALICYLIC ACID 2003#> 3 CM 01-701-1015 ACETYLSALICYLIC ACID 2003#> # i 66 more rowsExercise 5-4
Section titled “Exercise 5-4”The safety population has 254 rows before and after the join, and relationship = "one-to-one" checks that each subject has at most one COMPLT24 row. The week-24 completers are 60 on placebo, 30 on the high dose and 28 on the low dose. The other subjects have NA, because SUPPDM writes the flag only when it is Y.
# Exercise 5-4: the week-24 completers per arm, from SUPPDM joined to ADSLlibrary(dplyr)
comp24 <- pharmaversesdtm::suppdm |> filter(QNAM == "COMPLT24") |> select(USUBJID, COMP24FL = QVAL)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")adsl_c <- left_join(adsl, comp24, by = join_by(USUBJID), relationship = "one-to-one")c(before = nrow(adsl), after = nrow(adsl_c))#> before after#> 254 254
adsl_c |> count(TRT01A, COMP24FL)#> # A tibble: 6 x 3#> TRT01A COMP24FL n#> <chr> <chr> <int>#> 1 Placebo Y 60#> 2 Placebo <NA> 26#> 3 Xanomeline High Dose Y 30#> 4 Xanomeline High Dose <NA> 42#> 5 Xanomeline Low Dose Y 28#> 6 Xanomeline Low Dose <NA> 68Chapter 6
Section titled “Chapter 6”Back to chapter 6, summarise.
Exercise 6-1
Section titled “Exercise 6-1”Add TRT01A == "Placebo" to the filter(). The fifth subject is 01-701-1130, a man of 84. The first is 01-701-1015.
# Exercise 6-1: the first five subjects of the placebo armlibrary(dplyr)
pharmaverseadam::adsl |> filter(SAFFL == "Y", TRT01A == "Placebo") |> select(USUBJID, TRT01A, AGE, SEX, RACE) |> print(n = 5)#> # A tibble: 86 x 5#> USUBJID TRT01A AGE SEX RACE#> <chr> <chr> <dbl> <chr> <chr>#> 1 01-701-1015 Placebo 63 F WHITE#> 2 01-701-1023 Placebo 64 M WHITE#> 3 01-701-1047 Placebo 85 F WHITE#> 4 01-701-1118 Placebo 52 M WHITE#> 5 01-701-1130 Placebo 84 M WHITE#> # i 81 more rowsExercise 6-2
Section titled “Exercise 6-2”78 White subjects are in the placebo arm. count(TRT01A, RACE) gives one row per combination that exists. A combination with no subject (for example placebo and American Indian or Alaska Native) has no row at all.
# Exercise 6-2: race by treatment in the safety populationlibrary(dplyr)
pharmaverseadam::adsl |> filter(SAFFL == "Y") |> count(TRT01A, RACE)#> # A tibble: 7 x 3#> TRT01A RACE n#> <chr> <chr> <int>#> 1 Placebo BLACK OR AFRICAN AMERICAN 8#> 2 Placebo WHITE 78#> 3 Xanomeline High Dose AMERICAN INDIAN OR ALASKA NATIVE 1#> 4 Xanomeline High Dose BLACK OR AFRICAN AMERICAN 9#> 5 Xanomeline High Dose WHITE 62#> 6 Xanomeline Low Dose BLACK OR AFRICAN AMERICAN 6#> 7 Xanomeline Low Dose WHITE 90Exercise 6-3
Section titled “Exercise 6-3”No placebo subject had a serious TEAE: 0, 0%. The high dose has 1 subject (1.4%) and the low dose 2 (2.1%). Placebo has no row in the counts, so the left join gives NA for it. coalesce(n, 0L) turns that NA into 0. Without it, the placebo row would show NA for both n and pct. 0L is the whole number 0, the same type as n.
# Exercise 6-3: subjects with at least one serious TEAE, as a percent of the big Nlibrary(dplyr)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")adae <- pharmaverseadam::adae |> filter(SAFFL == "Y", TRTEMFL == "Y", AESER == "Y")
bign <- adsl |> count(TRT01A, name = "BIGN")n_ser <- adae |> group_by(TRT01A) |> summarise(n = n_distinct(USUBJID))
bign |> left_join(n_ser, by = join_by(TRT01A)) |> mutate(n = coalesce(n, 0L), pct = round(100 * n / BIGN, 1))#> # A tibble: 3 x 4#> TRT01A BIGN n pct#> <chr> <int> <int> <dbl>#> 1 Placebo 86 0 0#> 2 Xanomeline High Dose 72 1 1.4#> 3 Xanomeline Low Dose 96 2 2.1Exercise 6-4
Section titled “Exercise 6-4”19 subjects have a concomitant medication but no AE. The order of the arguments matters: setdiff(cm_subj, ae_subj) keeps the CM subjects that are not in AE. Program 06_8 asked the opposite question and got 15.
# Exercise 6-4: subjects with a concomitant medication but no AElibrary(dplyr)
ae_subj <- pharmaversesdtm::ae |> distinct(USUBJID)cm_subj <- pharmaversesdtm::cm |> distinct(USUBJID)
nrow(setdiff(cm_subj, ae_subj))#> [1] 19Chapter 7
Section titled “Chapter 7”Back to chapter 7, reshaping and lookups.
Exercise 7-1
Section titled “Exercise 7-1”There are 190 week-8 completers and 147 week-16 completers. The rule and .names do not change: only the list of columns grows.
# Exercise 7-1: two more population flags in the same across() calllibrary(dplyr)
pharmaversesdtm::suppdm |> tidyr::pivot_wider(id_cols = USUBJID, names_from = QNAM, values_from = QVAL) |> mutate(across( c(SAFETY, ITT, EFFICACY, COMPLT8, COMPLT16, COMPLT24), ~ if_else(.x == "Y", 1, 0, missing = 0), .names = "{.col}N" )) |> summarise(across(ends_with("N"), sum))#> # A tibble: 1 x 6#> SAFETYN ITTN EFFICACYN COMPLT8N COMPLT16N COMPLT24N#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>#> 1 254 254 234 190 147 118Exercise 7-2
Section titled “Exercise 7-2”Without the test, the missing age gets ">80". NA < 65 and NA <= 80 are both NA, not true, so case_when() goes on to .default. With is.na(AGE) first, the missing age gets "Missing". A missing age in the oldest group is a wrong count that no warning reports.
# Exercise 7-2: a missing age falls through to .defaultlibrary(dplyr)
ages <- tibble(AGE = c(63, NA, 85))
ages |> mutate( NO_CHECK = case_when(AGE < 65 ~ "<65", AGE <= 80 ~ "65-80", .default = ">80"), CHECKED = case_when( is.na(AGE) ~ "Missing", AGE < 65 ~ "<65", AGE <= 80 ~ "65-80", .default = ">80" ) )#> # A tibble: 3 x 3#> AGE NO_CHECK CHECKED#> <dbl> <chr> <chr>#> 1 63 <65 <65#> 2 NA >80 Missing#> 3 85 >80 >80Exercise 7-3
Section titled “Exercise 7-3”You get 9 value columns: three tests times three time points. The names join the two values with _: DIABP_815 is the diastolic blood pressure at time point 815 (after lying down for 5 minutes). Every cell now holds one value, so there is no warning.
# Exercise 7-3: names from two columns: one column per test and time pointlibrary(dplyr)
pharmaversesdtm::vs |> filter( USUBJID == "01-701-1015", VSBLFL == "Y", VSTESTCD %in% c("DIABP", "PULSE", "SYSBP") ) |> tidyr::pivot_wider( id_cols = USUBJID, names_from = c(VSTESTCD, VSTPTNUM), values_from = VSSTRESN )#> # A tibble: 1 x 10#> USUBJID DIABP_815 DIABP_816 DIABP_817 PULSE_815 PULSE_816 PULSE_817 SYSBP_815#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>#> 1 01-701-~ 56 51 61 56 59 59 130#> # i 2 more variables: SYSBP_816 <dbl>, SYSBP_817 <dbl>Exercise 7-4
Section titled “Exercise 7-4”143 F become Female and 111 M become Male. Counting the code and the text together shows that every code found its text. A code that is not in the named vector would give NA in SEXT.
# Exercise 7-4: a named vector turns the codes of SEX into textlibrary(dplyr)
sex_text <- c(F = "Female", M = "Male")
pharmaverseadam::adsl |> filter(SAFFL == "Y") |> mutate(SEXT = unname(sex_text[SEX])) |> count(SEX, SEXT)#> # A tibble: 2 x 3#> SEX SEXT n#> <chr> <chr> <int>#> 1 F Female 143#> 2 M Male 111Chapter 8
Section titled “Chapter 8”Back to chapter 8, functions.
Exercise 8-1
Section titled “Exercise 8-1”The function gives <65, 65-80, 65-80, >80 and Missing for 63, 65, 80, 81 and NA. On the safety population, the groups are 33, 144 and 77: the same as program 07_2. A function is vectorised when its body is, so it works inside mutate() on the whole column.
# Exercise 8-1: a function that makes the age group, used inside mutate()library(dplyr)
age_group <- function(age) { stopifnot(is.numeric(age)) case_when( is.na(age) ~ "Missing", age < 65 ~ "<65", age <= 80 ~ "65-80", .default = ">80" )}
age_group(c(63, 65, 80, 81, NA))#> [1] "<65" "65-80" "65-80" ">80" "Missing"
pharmaverseadam::adsl |> filter(SAFFL == "Y") |> mutate(AGEGR = age_group(AGE)) |> count(AGEGR)#> # A tibble: 3 x 2#> AGEGR n#> <chr> <int>#> 1 65-80 144#> 2 <65 33#> 3 >80 77Exercise 8-2
Section titled “Exercise 8-2”126 women are White (88.1%), and 17 are Black or African American. You filter the data before you give it to the function. The function itself does not change.
# Exercise 8-2: freq_one() on the female subjects onlylibrary(dplyr)
freq_one <- function(data, var) { data |> count({{ var }}) |> mutate(pct = round(100 * n / sum(n), 1))}
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")freq_one(adsl |> filter(SEX == "F"), RACE)#> # A tibble: 2 x 3#> RACE n pct#> <chr> <int> <dbl>#> 1 BLACK OR AFRICAN AMERICAN 17 11.9#> 2 WHITE 126 88.1Exercise 8-3
Section titled “Exercise 8-3”pct(65, 86) still gives 75.6. pct(5, 0) stops with total > 0 is not TRUE. Without the check, it gives Inf: a number that a table would print without complaint.
# Exercise 8-3: a check stops the function before it divides by zeropct <- function(n, total, digits = 1) { stopifnot(is.numeric(n), is.numeric(total), total > 0) round(100 * n / total, digits)}
pct(65, 86)#> [1] 75.6pct(5, 0)#> Error in pct(5, 0) : total > 0 is not TRUEExercise 8-4
Section titled “Exercise 8-4”5 placebo subjects had a severe TEAE, with 6 severe records between them. The filter goes before the call, and count_by() counts what it gets.
# Exercise 8-4: count_by() on the TEAEs of one arm, by severitylibrary(dplyr)source("R/count_by.R")
pharmaverseadam::adae |> filter(SAFFL == "Y", TRTEMFL == "Y", TRT01A == "Placebo") |> count_by(c(TRT01A, AESEV))#> # A tibble: 3 x 4#> TRT01A AESEV n_subj n_rec#> <chr> <chr> <int> <int>#> 1 Placebo MILD 58 210#> 2 Placebo MODERATE 25 65#> 3 Placebo SEVERE 5 6Exercise 8-5
Section titled “Exercise 8-5”map() gives three one-row data frames, and list_rbind() stacks them. all.equal() returns TRUE: the same n and mean age as group_by() with summarise(). check.attributes = FALSE is needed, because group_by() keeps the label of TRT01A from ADSL, and unique() does not.
# Exercise 8-5: map() over the arms; the result agrees with group_by()library(dplyr)library(purrr)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")arms <- sort(unique(adsl$TRT01A))
age_stats <- function(arm) { adsl |> filter(TRT01A == arm) |> summarise(TRT01A = arm, n = n(), mean = round(mean(AGE), 1))}
by_map <- map(arms, age_stats) |> list_rbind()by_map#> # A tibble: 3 x 3#> TRT01A n mean#> <chr> <int> <dbl>#> 1 Placebo 86 75.2#> 2 Xanomeline High Dose 72 73.8#> 3 Xanomeline Low Dose 96 76
by_group <- adsl |> group_by(TRT01A) |> summarise(n = n(), mean = round(mean(AGE), 1))all.equal(by_map, by_group, check.attributes = FALSE)#> [1] TRUEFound 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.