Skip to content

Answers, Part II (chapters 9 to 12)

Each answer has a program that was run, and its output. The programs read the ADaM data sets in programs/data/, so run the programs of chapters 9 to 12 first, in file order. Try the exercise yourself first. A different program that gives the same numbers is also a right answer.

programs/09_x1_trtdurd.R
# Answer 9-1: the duration of treatment in days. The first day counts, so add 1
library(dplyr)
adsl <- readRDS("data/adsl.rds") |>
mutate(TRTDURD = as.numeric(TRTEDT - TRTSDT) + 1)
adsl |>
filter(USUBJID == "01-701-1015") |>
select(USUBJID, TRTSDT, TRTEDT, TRTDURD)
#> # A tibble: 1 x 4
#> USUBJID TRTSDT TRTEDT TRTDURD
#> <chr> <date> <date> <dbl>
#> 1 01-701-1015 2014-01-02 2014-07-02 182
summary(adsl$TRTDURD)
#> Min. 1st Qu. Median Mean 3rd Qu. Max.
#> 1.00 46.25 133.50 116.09 183.00 212.00

For 01-701-1015, TRTDURD = 182. The + 1 counts the first day: a subject who takes the drug on one day only has a duration of 1 day, not 0. The summary shows exactly such a subject: the shortest duration is 1 day.

TRTEDT - TRTSDT is a difference of two dates, a time in days. as.numeric() makes it a plain number.

programs/09_x2_weightbl.R
# Answer 9-2: WEIGHTBL, the weight at baseline, as step 070 with one row per subject
library(dplyr)
adsl <- readRDS("data/adsl.rds")
vs_weightbl <- pharmaversesdtm::vs |>
filter(VSTESTCD == "WEIGHT", VSBLFL == "Y") |>
select(USUBJID, WEIGHTBL = VSSTRESN)
adsl_070 <- adsl |>
left_join(vs_weightbl, by = join_by(USUBJID), relationship = "one-to-one") |>
mutate(WEIGHTBL = round(WEIGHTBL, 1))
nrow(adsl_070)
#> [1] 254
adsl_070 |>
filter(USUBJID == "01-701-1015") |>
select(USUBJID, WEIGHTBL)
#> # A tibble: 1 x 2
#> USUBJID WEIGHTBL
#> <chr> <dbl>
#> 1 01-701-1015 54.4
adsl_070 |>
filter(is.na(WEIGHTBL)) |>
select(USUBJID, WEIGHTBL)
#> # A tibble: 1 x 2
#> USUBJID WEIGHTBL
#> <chr> <dbl>
#> 1 01-702-1082 NA

ADSL keeps its 254 rows: relationship = "one-to-one" found no subject with two baseline weights. Subject 01-701-1015 has WEIGHTBL = 54.4. Subject 01-702-1082 has no weight with VSBLFL == "Y", so WEIGHTBL is NA. Chapter 10 shows why: the SAP baseline rule takes its screening weight, but the SDTM flag VSBLFL does not. Ask the statistician which rule WEIGHTBL follows.

programs/09_x3_join_trap.R
# Answer 9-3: a join with EX, which has several rows per subject
library(dplyr)
adsl <- readRDS("data/adsl.rds")
ex <- pharmaversesdtm::ex |>
select(USUBJID, EXDOSE)
# without a promise: no message, but the rows are copied
check_1 <- left_join(adsl, ex, by = join_by(USUBJID))
nrow(check_1)
#> [1] 591
# the keys with more than one row, found before the join
ex |>
count(USUBJID) |>
filter(n > 1) |>
nrow()
#> [1] 226
# with the promise of add_vars(): R stops
check_2 <- adsl |>
left_join(ex, by = join_by(USUBJID), relationship = "one-to-one")
#> Error in `left_join()`:
#> ! Each row in `x` must match at most 1 row in `y`.
#> i Row 1 of `x` matches multiple rows in `y`.

The join without a promise gives 591 rows, one per EX row, and no message. 226 subjects have more than one EX row, so the join copies their ADSL row once for each EX row. With relationship = "one-to-one", R stops with an error and names the problem: a row of x (ADSL) matches several rows of y (EX). Choose the EX row you need first (the first dose, the last dose), then join.

programs/09_x4_simple_max.R
# Answer 9-4: the simple rule "TRTEDT is the latest EX end date that exists"
library(dplyr)
adsl <- readRDS("data/adsl.rds")
simple <- pharmaversesdtm::ex |>
mutate(EXENDT = lubridate::ymd(EXENDTC)) |>
summarise(TRTEDT_MAX = max(EXENDT, na.rm = TRUE), .by = USUBJID)
#> Warning:
#> There were 2 warnings in `summarise()`.
#> The first warning was:
#> i In argument: `TRTEDT_MAX = max(EXENDT, na.rm = TRUE)`.
#> i In group 86: `USUBJID = "01-705-1018"`.
#> Caused by warning in `max.default()`:
#> ! no non-missing arguments to max; returning -Inf
#> i Run `dplyr::last_dplyr_warnings()` to see the 1 remaining warning.
adsl |>
left_join(simple, by = join_by(USUBJID)) |>
filter(TRTEDT != TRTEDT_MAX | is.infinite(TRTEDT_MAX)) |>
select(USUBJID, TRTEDT, TRTEDT_MAX)
#> # A tibble: 6 x 3
#> USUBJID TRTEDT TRTEDT_MAX
#> <chr> <date> <date>
#> 1 01-704-1233 2013-07-14 2013-04-04
#> 2 01-705-1018 2013-07-12 -Inf
#> 3 01-705-1031 2014-05-11 2013-12-18
#> 4 01-705-1303 2014-06-02 2013-12-30
#> 5 01-705-1377 2014-03-07 2014-01-25
#> 6 01-705-1382 2013-05-13 -Inf

The same six subjects as in section 9.3 get another TRTEDT. For most of them, the simple rule gives the end of an earlier EX row. For 01-705-1018 and 01-705-1382, every EX row is open, so there is no end date at all: max() with na.rm = TRUE of nothing is -Inf, and R writes a warning. SAS would give a missing value without a message. These are the same six subjects that diffdf() found in section 9.7: the reference ADSL uses this simple rule.

programs/10_x1_anl01fl.R
# Answer 10-1: ANL01FL, one analysis row per subject, parameter, position, visit
library(dplyr)
advs <- readRDS("data/advs.rds")
advs_anl <- advs |>
arrange(USUBJID, PARAMCD, ATPTN, AVISITN, ADT, VSSEQ) |>
mutate(
ANL01FL = if_else(!is.na(AVISITN) & row_number() == n(), "Y", NA),
.by = c(USUBJID, PARAMCD, ATPTN, AVISITN)
)
# the groups with more than one row at an analysis visit
advs_anl |>
filter(!is.na(AVISITN)) |>
count(USUBJID, PARAMCD, ATPTN, AVISIT) |>
filter(n > 1)
#> # A tibble: 0 x 5
#> # i 5 variables: USUBJID <chr>, PARAMCD <chr>, ATPTN <dbl>, AVISIT <chr>,
#> # n <int>
advs_anl |>
count(PARAMCD, ANL01FL)
#> # A tibble: 8 x 3
#> PARAMCD ANL01FL n
#> <chr> <chr> <int>
#> 1 DIABP Y 5399
#> 2 DIABP <NA> 2808
#> 3 PULSE Y 5400
#> 4 PULSE <NA> 2804
#> 5 SYSBP Y 5400
#> 6 SYSBP <NA> 2808
#> 7 WEIGHT Y 1795
#> 8 WEIGHT <NA> 255

No group has more than one row: in the pilot, each subject has at most one value per parameter, position and analysis visit. So ANL01FL = "Y" is on every row with an analysis visit, and empty on the screening and unscheduled rows. The flag still belongs in ADVS. The rule must be in the program before the data has a second row at a visit, for example after a database update.

programs/10_x2_chg_all.R
# Answer 10-2: CHG on every row that has AVAL and BASE, also before and at baseline
library(dplyr)
advs <- readRDS("data/advs.rds") |>
filter(PARAMCD == "WEIGHT") |>
mutate(CHG_ALL = AVAL - BASE)
advs |>
summarise(
chg_after_baseline = sum(!is.na(CHG)),
chg_every_row = sum(!is.na(CHG_ALL))
)
#> # A tibble: 1 x 2
#> chg_after_baseline chg_every_row
#> <int> <int>
#> 1 1542 2050
advs |>
filter(USUBJID == "01-701-1015") |>
select(VISIT, AVAL, BASE, CHG, CHG_ALL) |>
print(n = 3)
#> # A tibble: 11 x 5
#> VISIT AVAL BASE CHG CHG_ALL
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 SCREENING 1 54.0 54.4 NA -0.450
#> 2 BASELINE 54.4 54.4 NA 0
#> 3 WEEK 2 53.1 54.4 -1.36 -1.36
#> # i 8 more rows

With the rule of chapter 10, 1542 weight rows have a CHG. With CHG on every row, all 2050 have one. On the baseline row CHG is 0, and on the screening row of 01-701-1015 it is -0.450. Both rules are allowed by ADaM; the specification decides.

programs/10_x3_shift_function.R
# Answer 10-3: the shift table as a function, called for ALT and for AST
library(dplyr)
adlb <- readRDS("data/adlb.rds")
shift_table <- function(adlb, paramcd) {
adlb |>
filter(PARAMCD == paramcd, AVISITN > 0, !is.na(ANRIND)) |>
summarise(
BNRIND = first(BNRIND),
WORST = case_when(
any(ANRIND == "HIGH") ~ "HIGH",
any(ANRIND == "LOW") ~ "LOW",
.default = "NORMAL"
),
.by = USUBJID
) |>
count(BNRIND, WORST) |>
tidyr::pivot_wider(names_from = WORST, values_from = n, values_fill = 0)
}
shift_table(adlb, "ALT")
#> # A tibble: 3 x 4
#> BNRIND HIGH NORMAL LOW
#> <chr> <int> <int> <int>
#> 1 HIGH 10 1 0
#> 2 LOW 0 1 0
#> 3 NORMAL 21 207 6
shift_table(adlb, "AST")
#> # A tibble: 2 x 3
#> BNRIND HIGH NORMAL
#> <chr> <int> <int>
#> 1 HIGH 10 7
#> 2 NORMAL 22 207

The function gives the ALT table of section 10.7 again: a test that the function works. For AST, 22 subjects with a normal value at baseline had a high value later. The AST table has no LOW column: no subject had a low AST.

programs/10_x4_no_filter.R
# Answer 10-4: ABLFL without the filter of restrict_derivation()
library(dplyr)
library(admiral)
advs <- readRDS("data/advs.rds") |>
filter(PARAMCD == "WEIGHT") |>
select(-ABLFL) |>
derive_var_extreme_flag(
by_vars = exprs(USUBJID, PARAMCD, ATPTN), order = exprs(ADT, VSSEQ),
new_var = ABLFL, mode = "last"
)
advs |>
filter(ABLFL == "Y") |>
count(VISIT)
#> # A tibble: 11 x 2
#> VISIT n
#> <chr> <int>
#> 1 AMBUL ECG REMOVAL 1
#> 2 BASELINE 5
#> 3 WEEK 12 25
#> 4 WEEK 16 18
#> 5 WEEK 2 23
#> 6 WEEK 20 13
#> 7 WEEK 24 5
#> 8 WEEK 26 111
#> 9 WEEK 4 17
#> 10 WEEK 6 19
#> 11 WEEK 8 17

Without the filter, derive_var_extreme_flag() flags the last row of every subject: in most cases a row after the first dose, such as Week 26. Only 5 flags fall on the BASELINE visit. The filter of restrict_derivation() is what makes the flag a baseline flag: only the rows on or before the first dose can be the last one.

programs/11_x1_serious.R
# Answer 11-1: subjects with a treatment-emergent serious event, two ways
library(dplyr)
adae <- readRDS("data/adae.rds")
# count each subject once
adae |>
filter(TRTEMFL == "Y", AESER == "Y") |>
summarise(subjects = n_distinct(USUBJID))
#> # A tibble: 1 x 1
#> subjects
#> <int>
#> 1 3
# AOCCFL marks the first event of a subject, serious or not
adae |>
filter(AOCCFL == "Y", AESER == "Y") |>
nrow()
#> [1] 1

3 subjects had a treatment-emergent serious event. But only 1 serious row has AOCCFL = "Y". AOCCFL marks the first treatment-emergent event of a subject, of any kind. For the other subjects, an event that was not serious came first. To count subjects with a serious event, filter the serious events first and then count each subject once, or derive a flag for that purpose.

programs/11_x2_aoccsfl.R
# Answer 11-2: AOCCSFL marks one event per subject and system organ class
library(dplyr)
adae <- readRDS("data/adae.rds")
adae |>
filter(AOCCSFL == "Y") |>
nrow()
#> [1] 550
adae |>
filter(TRTEMFL == "Y") |>
distinct(USUBJID, AEBODSYS) |>
nrow()
#> [1] 550

550 rows have AOCCSFL = "Y", and there are 550 distinct pairs of subject and system organ class among the treatment-emergent events. A table of subjects by system organ class can count the rows with AOCCSFL = "Y".

programs/11_x3_window.R
# Answer 11-3: the reference rule, with a window of 30 days after the last dose
library(dplyr)
library(admiral)
adae <- readRDS("data/adae.rds") |>
derive_var_trtemfl(
new_var = TRTEM30FL, start_date = ASTDT, end_date = AENDT,
trt_start_date = TRTSDT, trt_end_date = TRTEDT, end_window = 30
)
adae |>
count(TRTEMFL, TRTEM30FL)
#> # A tibble: 2 x 3
#> TRTEMFL TRTEM30FL n
#> <chr> <chr> <int>
#> 1 Y Y 1126
#> 2 <NA> <NA> 65

No event changes. With your TRTEDT, no treatment-emergent event starts more than 30 days after the last dose. So the four differences from the reference in section 11.4 come from TRTEDT in ADSL, not from the window.

programs/11_x4_floor.R
# Answer 11-4: a start date "2013-03" and a first dose on 18 March 2013
library(dplyr)
library(admiral)
cases <- tibble(
USUBJID = c("A", "B"),
AESTDTC = c("2013-03", "2013-02"),
TRTSDT = as.Date(c("2013-03-18", "2013-03-18"))
)
cases |>
derive_vars_dt(
dtc = AESTDTC, new_vars_prefix = "AST", highest_imputation = "M",
date_imputation = "first", min_dates = exprs(TRTSDT)
) |>
mutate(TRTEMFL = if_else(ASTDT >= TRTSDT, "Y", NA))
#> # A tibble: 2 x 6
#> USUBJID AESTDTC TRTSDT ASTDT ASTDTF TRTEMFL
#> <chr> <chr> <date> <date> <chr> <chr>
#> 1 A 2013-03 2013-03-18 2013-03-18 D Y
#> 2 B 2013-02 2013-03-18 2013-02-01 D <NA>

Subject A: 2013-03 has the same month as the first dose. The event may have started after the dose, so min_dates sets ASTDT to the first dose, 2013-03-18, and TRTEMFL = "Y". This is the worst case: when you cannot know, the event counts. Subject B: 2013-02 is before the month of the first dose, so ASTDT is 2013-02-01 and the event is not treatment emergent. Both have ASTDTF = "D".

programs/12_x1_check_events.R
# Answer 12-1: check the event source before you trust AVAL
library(dplyr)
adsl <- readRDS("data/adsl.rds") |>
select(USUBJID, RFENDT)
derm <- readRDS("data/adae.rds") |>
filter(
TRTEMFL == "Y",
grepl("APPLICATION|DERMATITIS|ERYTHEMA|BLISTER", AEDECOD) |
(AEBODSYS == "SKIN AND SUBCUTANEOUS TISSUE DISORDERS" &
!AEDECOD %in% c("COLD SWEAT", "HYPERHIDROSIS", "ALOPECIA"))
) |>
left_join(adsl, by = join_by(USUBJID), relationship = "many-to-one")
derm |>
summarise(
events = n(),
no_start_date = sum(is.na(ASTDT)),
imputed_start = sum(!is.na(ASTDTF)),
after_end_of_study = sum(ASTDT > RFENDT)
)
#> # A tibble: 1 x 4
#> events no_start_date imputed_start after_end_of_study
#> <int> <int> <int> <int>
#> 1 476 0 0 0

All 476 events have a start date, none is imputed, and none starts after the end of study. So every AVAL of an event is a real number of days, inside the study. In another study, an event with a missing start date would get no ADT and no AVAL. Find such events before the derivation, and ask for a rule.

programs/12_x2_ttsae.R
# Answer 12-2: time to the first treatment-emergent serious adverse event (TTSAE)
library(dplyr)
library(admiral)
adsl <- readRDS("data/adsl.rds") |>
filter(SAFFL == "Y")
adae <- readRDS("data/adae.rds")
sae <- event_source(
dataset_name = "adae",
filter = TRTEMFL == "Y" & AESER == "Y",
date = ASTDT,
set_values_to = exprs(
EVNTDESC = "Serious adverse event", SRCDOM = "ADAE", SRCVAR = "ASTDT"
)
)
end_of_study <- censor_source(
dataset_name = "adsl",
date = RFENDT,
set_values_to = exprs(
EVNTDESC = "Study completion date", SRCDOM = "ADSL", SRCVAR = "RFENDT"
)
)
derive_param_tte(
dataset_adsl = adsl,
event_conditions = list(sae),
censor_conditions = list(end_of_study),
source_datasets = list(adsl = adsl, adae = adae),
set_values_to = exprs(
PARAMCD = "TTSAE", PARAM = "Time to First Serious Adverse Event"
)
) |>
count(PARAMCD, CNSR, EVNTDESC)
#> # A tibble: 2 x 4
#> PARAMCD CNSR EVNTDESC n
#> <chr> <int> <chr> <int>
#> 1 TTSAE 0 Serious adverse event 3
#> 2 TTSAE 1 Study completion date 251

3 subjects had a treatment-emergent serious adverse event; 251 are censored at the end of study. A new parameter is one more event_source() and one more call. derive_param_tte() applies the same rules.

programs/12_x3_window.R
# Answer 12-3: the dermatologic events of the first 12 weeks (days 1 to 84)
library(dplyr)
adsl <- readRDS("data/adsl.rds") |>
filter(SAFFL == "Y") |>
select(USUBJID, TRTSDT, RFENDT) |>
mutate(WEEK12DT = TRTSDT + 83)
# first the events inside the window, then the first one of them
first_derm <- readRDS("data/adae.rds") |>
filter(
TRTEMFL == "Y",
grepl("APPLICATION|DERMATITIS|ERYTHEMA|BLISTER", AEDECOD) |
(AEBODSYS == "SKIN AND SUBCUTANEOUS TISSUE DISORDERS" &
!AEDECOD %in% c("COLD SWEAT", "HYPERHIDROSIS", "ALOPECIA"))
) |>
left_join(adsl, by = join_by(USUBJID), relationship = "many-to-one") |>
filter(ASTDT <= WEEK12DT) |>
arrange(USUBJID, ASTDT, AESEQ) |>
slice_head(n = 1, by = USUBJID) |>
select(USUBJID, ASTDT)
adtte12 <- adsl |>
left_join(first_derm, by = join_by(USUBJID), relationship = "one-to-one") |>
mutate(
ADT = case_when(
!is.na(ASTDT) ~ ASTDT,
RFENDT <= WEEK12DT ~ RFENDT,
.default = WEEK12DT
),
CNSR = if_else(!is.na(ASTDT), 0L, 1L),
EVNTDESC = case_when(
!is.na(ASTDT) ~ "Dermatologic event",
RFENDT <= WEEK12DT ~ "Study completion date",
.default = "End of at-risk period"
),
AVAL = as.numeric(ADT - TRTSDT) + 1
)
adtte12 |>
count(CNSR, EVNTDESC)
#> # A tibble: 3 x 3
#> CNSR EVNTDESC n
#> <int> <chr> <int>
#> 1 0 Dermatologic event 139
#> 2 1 End of at-risk period 69
#> 3 1 Study completion date 46
adtte12 |>
filter(USUBJID %in% c("01-701-1015", "01-701-1033", "01-705-1059")) |>
select(USUBJID, TRTSDT, WEEK12DT, RFENDT, ADT, AVAL, CNSR)
#> # A tibble: 3 x 7
#> USUBJID TRTSDT WEEK12DT RFENDT ADT AVAL CNSR
#> <chr> <date> <date> <date> <date> <dbl> <int>
#> 1 01-701-1015 2014-01-02 2014-03-26 2014-07-02 2014-01-03 2 0
#> 2 01-701-1033 2014-03-18 2014-06-09 2014-04-14 2014-04-14 28 1
#> 3 01-705-1059 2013-08-05 2013-10-27 2013-12-05 2013-10-27 84 1

In 12 weeks, 139 subjects have a dermatologic event, not 152. 69 subjects are censored at the end of the window, and 46 at the end of study, because their study ended inside the window.

Subject 01-705-1059 had its first dermatologic event after day 84. Inside the window it was free of the event, so it is censored at the end of the window, 2013-10-27, with AVAL = 84. The program keeps the events inside the window first, and only then takes the first one. If it took the first event of the whole study first, this subject would have no event and no censoring date in the window.

In admiral, the end_dates argument of derive_param_tte() limits the events and the censorings to a window.

programs/12_x4_km.R
# Answer 12-4: what ADTTE is for. Events per arm, and the Kaplan-Meier estimate
library(dplyr)
library(survival)
adsl <- readRDS("data/adsl.rds") |>
select(USUBJID, TRT01A)
adtte <- readRDS("data/adtte.rds") |>
left_join(adsl, by = join_by(USUBJID), relationship = "one-to-one")
adtte |>
count(TRT01A, CNSR)
#> # A tibble: 6 x 3
#> TRT01A CNSR n
#> <chr> <int> <int>
#> 1 Placebo 0 29
#> 2 Placebo 1 57
#> 3 Xanomeline High Dose 0 60
#> 4 Xanomeline High Dose 1 12
#> 5 Xanomeline Low Dose 0 63
#> 6 Xanomeline Low Dose 1 33
# Surv() wants 1 for an event: the opposite of CNSR
survfit(Surv(AVAL, 1 - CNSR) ~ TRT01A, data = adtte)
#> Call: survfit(formula = Surv(AVAL, 1 - CNSR) ~ TRT01A, data = adtte)
#>
#> n events median 0.95LCL 0.95UCL
#> TRT01A=Placebo 86 29 NA NA NA
#> TRT01A=Xanomeline High Dose 72 60 31 23 46
#> TRT01A=Xanomeline Low Dose 96 63 34 28 51

Placebo has 29 events among 86 subjects. The high dose has 60 among 72, the low dose 63 among 96. The arms come from TRT01A, the actual treatment, so the low dose has the 12 subjects who were planned for the high dose. The median time to the first dermatologic event is 31 days on the high dose and 34 days on the low dose. On placebo fewer than half of the subjects had an event, so the median is NA: the curve never reaches 50%.

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.