Answers, Parts IV and V (chapters 15 to 19)
Each answer has a program that was run, and its output. The programs of chapters 15 and 16 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.
Chapter 15
Section titled “Chapter 15”Exercise 15-1
Section titled “Exercise 15-1”# Answer 15-1: TRTDURD by a second way, compared with the referencelibrary(dplyr)library(diffdf)
ours <- readRDS("data/adsl.rds") |> transmute(USUBJID, TRTDURD = as.numeric(TRTEDT - TRTSDT) + 1) |> haven::zap_label()ref <- pharmaverseadam::adsl |> filter(ARMCD != "Scrnfail") |> select(USUBJID, TRTDURD) |> haven::zap_label()
ours |> filter(USUBJID == "01-701-1015")#> # A tibble: 1 x 2#> USUBJID TRTDURD#> <chr> <dbl>#> 1 01-701-1015 182diffdf(ours, ref, keys = "USUBJID")#> Warning message:#> In diffdf(ours, ref, keys = "USUBJID") :#> Not all Values Compared Equal#> Differences found between the objects!#>#> Summary of BASE and COMPARE#> ==================================================================#> PROPERTY BASE COMP#> ------------------------------------------------------------------#> Name ours ref#> Class "tbl_df, tbl, data.frame" "tbl_df, tbl, data.frame"#> Rows(#) 254 254#> Columns(#) 2 2#> ------------------------------------------------------------------#>#>#> Not all Values Compared Equal#> =============================#> Variable No of Differences#> -----------------------------#> TRTDURD 6#> -----------------------------#>#>#> ======================================#> VARIABLE USUBJID BASE COMPARE#> --------------------------------------#> TRTDURD 01-704-1233 116 15#> TRTDURD 01-705-1018 8 NA#> TRTDURD 01-705-1031 166 22#> TRTDURD 01-705-1303 169 15#> TRTDURD 01-705-1377 63 22#> TRTDURD 01-705-1382 1 NA#> --------------------------------------#>For 01-701-1015, TRTDURD = 182 in both. Six subjects differ, and they are the six of TRTEDT in section 15.6. TRTDURD is computed from TRTEDT, so a rule of TRTEDT becomes a difference of TRTDURD. For 01-705-1018 and 01-705-1382 the reference has no TRTEDT, so it has no TRTDURD either. Write this as part of finding 15-01, not as a new finding: it has the same cause.
Exercise 15-2
Section titled “Exercise 15-2”# Answer 15-2: cut() with right = FALSE moves the boundary to the other endlibrary(dplyr)library(diffdf)
prod <- readRDS("data/adsl.rds") |> select(USUBJID, AGE, AGEGR1) |> haven::zap_label()
qc <- prod |> mutate(AGEGR1 = as.character(cut( AGE, breaks = c(-Inf, 65, 80, Inf), labels = c("<65", "65-80", ">80"), right = FALSE )))
res <- diffdf(prod, qc, keys = "USUBJID")#> Warning message:#> In diffdf(prod, qc, keys = "USUBJID") :#> Not all Values Compared Equalres$NumDiff#> # A tibble: 1 x 2#> Variable `No of Differences`#> * <chr> <int>#> 1 AGEGR1 11res$VarDiff_AGEGR1 |> left_join(prod |> select(USUBJID, AGE), by = join_by(USUBJID)) |> count(AGE, BASE, COMPARE)#> # A tibble: 1 x 4#> AGE BASE COMPARE n#> <dbl> <chr> <chr> <int>#> 1 80 65-80 >80 11With right = FALSE, each interval is closed on the left: [65, 80) holds 65 to 79. Now the 4 subjects aged 65 are right, but 11 subjects aged 80 move to >80. The boundary moved from one end to the other. For whole years, the right break points are 64 and 80 with the default right = TRUE, as in program 15_1. A full compare finds either mistake.
Exercise 15-3
Section titled “Exercise 15-3”# Answer 15-3: the EX rows of the six subjects behind the TRTEDT differenceslibrary(dplyr)
ours <- readRDS("data/adsl.rds") |> select(USUBJID, TRTEDT)ref <- pharmaverseadam::adsl |> select(USUBJID, TRTEDT_REF = TRTEDT)
six <- inner_join(ours, ref, by = join_by(USUBJID)) |> filter(!TRTEDT %in% TRTEDT_REF | is.na(TRTEDT_REF)) |> pull(USUBJID) |> as.character()six#> [1] "01-704-1233" "01-705-1018" "01-705-1031" "01-705-1303" "01-705-1377"#> [6] "01-705-1382"
pharmaversesdtm::ex |> filter(USUBJID %in% six) |> select(USUBJID, EXSEQ, EXSTDTC, EXENDTC) |> print(n = 30)#> # A tibble: 10 x 4#> USUBJID EXSEQ EXSTDTC EXENDTC#> <chr> <dbl> <chr> <chr>#> 1 01-704-1233 1 2013-03-21 2013-04-04#> 2 01-704-1233 2 2013-04-05 <NA>#> 3 01-705-1018 1 2013-07-05 <NA>#> 4 01-705-1031 1 2013-11-27 2013-12-18#> 5 01-705-1031 2 2013-12-19 <NA>#> 6 01-705-1303 1 2013-12-16 2013-12-30#> 7 01-705-1303 2 2013-12-31 <NA>#> 8 01-705-1377 1 2014-01-04 2014-01-25#> 9 01-705-1377 2 2014-01-26 <NA>#> 10 01-705-1382 1 2013-05-13 <NA>All six subjects have an EX row without an end date (EXENDTC is NA), and it is always their last row. For 01-705-1018 and 01-705-1382 it is the only row. This is the “open dose row” of section 9.3. The list is the evidence for the finding note of section 15.7.
Exercise 15-4
Section titled “Exercise 15-4”# Answer 15-4: the log check also records an error, and then stops readinglibrary(dplyr)
check_log <- function(file) { found <- tibble(kind = character(), text = character()) keep <- function(kind, cnd) { text <- gsub("\\s+", " ", conditionMessage(cnd)) found <<- add_row(found, kind = kind, text = substr(text, 1, 60)) } tryCatch( withCallingHandlers( source(file, local = new.env()), warning = function(w) { keep("WARNING", w) invokeRestart("muffleWarning") }, message = function(m) { keep("MESSAGE", m) invokeRestart("muffleMessage") } ), error = function(e) keep("ERROR", e) ) found}
prog <- tempfile(fileext = ".R")writeLines(c( "x <- mean(c('a', 'b'))", "adsl <- dplyr::filter(pharmaverseadam::adsl, AEG > 80)", "y <- 1"), prog)
check_log(prog)#> # A tibble: 2 x 2#> kind text#> <chr> <chr>#> 1 WARNING argument is not numeric or logical: returning NA#> 2 ERROR i In argument: `AEG > 80`. Caused by error: ! object 'AEG' ntryCatch() around withCallingHandlers() catches the error, and keep() writes it as a row of kind ERROR. The test program has a warning (the mean of a text) and an error (AEG is not a column). The third line, y <- 1, never runs: R stops a program at its first error, so the check stops reading too. That is also what a reviewer must know: everything after the error is missing.
Exercise 15-5
Section titled “Exercise 15-5”# Answer 15-5: the AVAL rule, written as the data needs itlibrary(dplyr)
advs <- readRDS("data/advs.rds") |> left_join( pharmaversesdtm::vs |> select(USUBJID, VSSEQ, VSSTAT), by = join_by(USUBJID, VSSEQ) )
# AVAL may be missing only when the test was not done, and then must beadvs |> summarise( missing_not_explained = sum(is.na(AVAL) & !VSSTAT %in% "NOT DONE"), not_done_with_value = sum(!is.na(AVAL) & VSSTAT %in% "NOT DONE") )#> # A tibble: 1 x 2#> missing_not_explained not_done_with_value#> <int> <int>#> 1 0 0Both counts are 0: every missing AVAL is explained by VSSTAT = "NOT DONE", and no test that was not done has a value. ADVS passes. The rule now says what the data must be, not what is easy to count.
Chapter 16
Section titled “Chapter 16”Exercise 16-1
Section titled “Exercise 16-1”# Answer 16-1: check 9, weights outside a plausible rangelibrary(dplyr)
weight <- pharmaversesdtm::vs |> filter(VSTESTCD == "WEIGHT")
range(weight$VSSTRESN)#> [1] 33.11 107.96weight |> filter(VSSTRESN < 30 | VSSTRESN > 200) |> nrow()#> [1] 0The weights go from 33.11 kg to 107.96 kg, and 0 weights are outside 30 to 200 kg. The assumption holds. A plausibility check like this finds a weight in pounds or a typo with one digit too many.
Exercise 16-2
Section titled “Exercise 16-2”# Answer 16-2: a new decision D1: only a weight strictly before the doselibrary(dplyr)
adsl <- readRDS("data/adsl.rds")
wt_010 <- pharmaversesdtm::vs |> filter(VSTESTCD == "WEIGHT", !is.na(VSSTRESN)) |> transmute(USUBJID, VSSEQ, VISIT, ADT = as.Date(VSDTC), AVAL = VSSTRESN) |> inner_join(select(adsl, USUBJID, TRTSDT), by = join_by(USUBJID))
# Step 020 is the only step that changes: < instead of <=wt_020 <- wt_010 |> filter(ADT < TRTSDT) |> arrange(USUBJID, ADT, VSSEQ) |> slice_tail(n = 1, by = USUBJID)
adsl_wt <- adsl |> left_join( wt_020 |> select(USUBJID, WEIGHTBL = AVAL, WTBLVIS = VISIT), by = join_by(USUBJID), relationship = "one-to-one" )count(adsl_wt, WTBLVIS)#> # A tibble: 1 x 2#> WTBLVIS n#> <chr> <int>#> 1 SCREENING 1 254adsl_wt |> filter(USUBJID == "01-701-1015") |> select(USUBJID, WEIGHTBL, WTBLVIS)#> # A tibble: 1 x 3#> USUBJID WEIGHTBL WTBLVIS#> <chr> <dbl> <chr>#> 1 01-701-1015 54.0 SCREENING 1Only step 020 changes: < instead of <=. Steps 010 and 030 stay the same, and so does the program header, except decision D1 and a new line in the change log. Now all 254 baselines come from SCREENING 1, because the BASELINE weight was always taken on the day of the first dose. 01-701-1015 gets 54.0 kg instead of 54.4 kg. One decision changes the baseline of every subject: that is why D1 must be written down and agreed.
Exercise 16-3
Section titled “Exercise 16-3”# Answer 16-3: the check program for HEIGHTBL, before any derivationlibrary(dplyr)
adsl <- readRDS("data/adsl.rds") |> select(USUBJID, TRTSDT)height <- pharmaversesdtm::vs |> filter(VSTESTCD == "HEIGHT") |> inner_join(adsl, by = join_by(USUBJID))
count(height, VISIT, VSSTRESU)#> # A tibble: 1 x 3#> VISIT VSSTRESU n#> <chr> <chr> <int>#> 1 SCREENING 1 cm 254no_height <- anti_join(adsl, height, by = join_by(USUBJID))two_heights <- count(height, USUBJID) |> filter(n > 1)after_dose <- filter(height, as.Date(VSDTC) > TRTSDT)
tribble( ~check, ~n, "subjects without a height", nrow(no_height), "subjects with more than one height", nrow(two_heights), "heights after the first dose", nrow(after_dose), "heights without a value", sum(is.na(height$VSSTRESN)))#> # A tibble: 4 x 2#> check n#> <chr> <int>#> 1 subjects without a height 0#> 2 subjects with more than one height 0#> 3 heights after the first dose 0#> 4 heights without a value 0The height is measured once, at SCREENING 1, in cm, for all 254 subjects. All four checks give 0. So HEIGHTBL needs no baseline rule: it is the one height of the subject. Write that in the note too, so that a later data delivery with a second height is found by the check.
Exercise 16-4
Section titled “Exercise 16-4”# Answer 16-4: BMIBL from WEIGHTBL and the height, compared with the referencelibrary(dplyr)library(diffdf)
adsl_wt <- readRDS("data/16_adsl_weightbl.rds")
# Step 040: the height of each subject (one per subject: exercise 16-3)height <- pharmaversesdtm::vs |> filter(VSTESTCD == "HEIGHT") |> select(USUBJID, HEIGHTBL = VSSTRESN)
# Step 050: BMI = weight in kg / (height in m) squaredours <- adsl_wt |> left_join(height, by = join_by(USUBJID), relationship = "one-to-one") |> transmute(USUBJID, BMIBL = WEIGHTBL / (HEIGHTBL / 100)^2) |> haven::zap_label()ours |> filter(USUBJID == "01-701-1015")#> # A tibble: 1 x 2#> USUBJID BMIBL#> <chr> <dbl>#> 1 01-701-1015 25.1
ref <- pharmaverseadam::advs |> filter(PARAMCD == "BMI", ABLFL == "Y") |> select(USUBJID, BMIBL = AVAL) |> haven::zap_label()diffdf(ours, ref, keys = "USUBJID")#> No issues were found!BMIBL of 01-701-1015 is 25.1. The compare with the baseline BMI of the reference ADVS finds no issues for the 254 subjects. Steps 040 and 050 read the result of step 030: the numbered steps make the new variable one more step, not a new program.
Chapter 17
Section titled “Chapter 17”Exercise 17-1
Section titled “Exercise 17-1”# Answer 17-1: a default is evaluated when it is first used, not when the call startsf <- function(a, b = a * 2) { a <- 10 b}f(1)#> [1] 20
g <- function(a, b = a * 2) { force(b) # evaluate b now, while a is still 1 a <- 10 b}g(1)#> [1] 2f(1) gives 20, not 2. The default b = a * 2 is evaluated when the body first uses b, and by then the body has set a to 10. With force(b) as the first line, R evaluates b at once, while a is still 1: g(1) gives 2.
Exercise 17-2
Section titled “Exercise 17-2”# Answer 17-2: a variable with the name of a column. The column wins in filter()library(dplyr)
alt <- pharmaverseadam::adlb |> filter(PARAMCD == "ALT", !is.na(AVAL), is.na(DTYPE))
ANRHI <- 40alt |> filter(AVAL > ANRHI) |> nrow() # the column ANRHI of each row#> [1] 83alt |> filter(AVAL > .env$ANRHI) |> nrow() # the value 40#> [1] 58filter(AVAL > ANRHI) keeps 83 rows: ANRHI is the column, the upper limit of each row. The variable of the program is hidden by the column. filter(AVAL > .env$ANRHI) uses the value 40 and keeps 58 rows. No error and no warning tell you which one you got. Use .env$ or another name.
Exercise 17-3
Section titled “Exercise 17-3”# Answer 17-3: a column name made from a name and a value, with :=library(dplyr)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")
n_over <- function(data, var, limit, by) { data |> summarise( "n_{{ var }}_over_{limit}" := sum({{ var }} > limit, na.rm = TRUE), .by = {{ by }} )}n_over(adsl, AGE, 80, ARM)#> # A tibble: 3 x 2#> ARM n_AGE_over_80#> <chr> <int>#> 1 Placebo 30#> 2 Xanomeline High Dose 18#> 3 Xanomeline Low Dose 29n_over(adsl, TRTDURD, 180, ARM)#> # A tibble: 3 x 2#> ARM n_TRTDURD_over_180#> <chr> <int>#> 1 Placebo 53#> 2 Xanomeline High Dose 24#> 3 Xanomeline Low Dose 24"n_{{ var }}_over_{limit}" := builds the name from the argument and the value. 30 placebo subjects, 18 on the high dose and 29 on the low dose are older than 80. The same function gives n_TRTDURD_over_180 for the treatment duration.
Exercise 17-4
Section titled “Exercise 17-4”# Answer 17-4: mean_of() for a name in a text, with .data[[ ]]library(dplyr)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")
mean_of_text <- function(data, var) { data |> summarise(mean = round(mean(.data[[var]]), 1))}mean_of_text(adsl, "AGE")#> # A tibble: 1 x 1#> mean#> <dbl>#> 1 75.1
# Or turn the text into a name first: rlang::sym(), then !!mean_of <- function(data, var) { data |> summarise(mean = round(mean({{ var }}), 1))}mean_of(adsl, !!rlang::sym("AGE"))#> # A tibble: 1 x 1#> mean#> <dbl>#> 1 75.1Two ways give the same mean, 75.1:
.data[[var]]in the function: the caller gives a text.!!rlang::sym("AGE")in the call:sym()turns the text into a name, and!!puts the name in. The function keeps its{{ }}.
The first way is the usual one. Use the second when you cannot change the function.
Chapter 18
Section titled “Chapter 18”Exercise 18-1
Section titled “Exercise 18-1”# Answer 18-1: leave some parameters out. Build the list without themlibrary(dplyr)library(purrr)
exclude <- c("HEIGHT", "TEMP")
bl <- pharmaverseadam::advs |> filter(ABLFL == "Y", is.na(ATPTN) | ATPTN == 815, !PARAMCD %in% exclude)
tables <- split(bl, bl$PARAMCD) |> map(\(d) summarise(d, n = n(), mean = round(mean(AVAL), 1), .by = TRT01P))length(tables)#> [1] 7names(tables)#> [1] "BMI" "BSA" "DIABP" "MAP" "PULSE" "SYSBP" "WEIGHT"7 tables are left. !PARAMCD %in% exclude removes the rows before split(), so the list never has the two parameters. A test inside the function would leave an empty element or a NULL in the list.
Exercise 18-2
Section titled “Exercise 18-2”# Answer 18-2: imap() gives each element and its name: a title per tablelibrary(dplyr)library(purrr)
bl <- pharmaverseadam::advs |> filter(ABLFL == "Y", is.na(ATPTN) | ATPTN == 815)by_param <- split(bl, bl$PARAMCD)
iwalk(by_param, \(d, code) { cat(sprintf("%-7s n = %d, mean = %.1f\n", code, nrow(d), mean(d$AVAL)))})#> BMI n = 254, mean = 24.7#> BSA n = 254, mean = 1.7#> DIABP n = 254, mean = 76.4#> HEIGHT n = 254, mean = 163.9#> MAP n = 254, mean = 97.3#> PULSE n = 254, mean = 69.7#> SYSBP n = 254, mean = 139.2#> TEMP n = 254, mean = 36.6#> WEIGHT n = 254, mean = 66.6iwalk() calls the function with two arguments: the element (d) and its name (code). Each parameter has 254 baseline rows in the lying-down position, one per subject. The mean baseline weight of all arms together is 66.6 kg.
Exercise 18-3
Section titled “Exercise 18-3”# Answer 18-3: switch DIABP on in a copy of the parameter file, run againlibrary(dplyr)library(purrr)
settings <- "data/18_run_settings.csv" |> readr::read_csv(show_col_types = FALSE) |> mutate(include = if_else(paramcd == "DIABP", "Y", include))file <- tempfile(fileext = ".csv")readr::write_csv(settings, file)
bl <- pharmaverseadam::advs |> filter(ABLFL == "Y", is.na(ATPTN) | ATPTN == 815)
readr::read_csv(file, show_col_types = FALSE) |> filter(include == "Y", paramcd == "DIABP") |> pwalk(\(paramcd, dec, title, ...) { cat(title, "\n") bl |> filter(PARAMCD == paramcd) |> summarise( n = n(), mean = formatC(mean(AVAL), format = "f", digits = dec + 1), .by = TRT01P ) |> arrange(TRT01P) |> print() })#> Baseline diastolic blood pressure (mmHg)#> # A tibble: 3 x 3#> TRT01P n mean#> <chr> <int> <chr>#> 1 Placebo 86 75.7#> 2 Xanomeline High Dose 84 77.2#> 3 Xanomeline Low Dose 84 76.3The mean baseline diastolic blood pressure on placebo is 75.7 mmHg, with dec = 0 in the file, so one decimal. The same numbers came from split() and map() in program 18_2. Only the copy of the settings changed, not the code.
Exercise 18-4
Section titled “Exercise 18-4”# Answer 18-4: the variables in one data set only, both wayslibrary(dplyr)
spec <- tibble(name = names(pharmaverseadam::adsl))ours <- tibble(name = names(readRDS("data/adsl.rds")))
only_spec <- anti_join(spec, ours, by = join_by(name))only_ours <- anti_join(ours, spec, by = join_by(name))nrow(only_spec)#> [1] 37head(only_spec$name, 5)#> [1] "COUNTRY" "RFXSTDTC" "RFXENDTC" "RFPENDTC" "SCRFDT"nrow(only_ours)#> [1] 7only_ours$name#> [1] "TRT01PN" "TRT01AN" "ITTFL" "EFFFL" "COMP24FL" "DCSREAS" "RFENDT"37 variables of the reference ADSL are not in your ADSL, such as COUNTRY and RFXSTDTC. 7 of your variables are not in the reference: the numeric treatments TRT01PN and TRT01AN, the flags ITTFL, EFFFL and COMP24FL, DCSREAS and RFENDT. In a study, the specification decides: a variable in the specification must be in the data, and a variable in the data needs a row in the specification.
Chapter 19
Section titled “Chapter 19”Exercise 19-1
Section titled “Exercise 19-1”# Answer 19-1: test first. A by column that does not exist: red, then greenlibrary(dplyr)
copy <- file.path(tempdir(), "studylib_x1")unlink(copy, recursive = TRUE)dir.create(copy)files <- list.files("studylib", full.names = TRUE)invisible(file.copy(files, copy, recursive = TRUE))
# 1. The test, written before the codetest_file <- file.path(copy, "tests", "testthat", "test-by.R")writeLines(c( 'test_that("count_subj() names a by column that does not exist", {', ' adae <- pharmaverseadam::adae', ' expect_error(count_subj(adae, ARMX), "column of .*by.* is not in")', '})'), test_file)
pkgload::load_all(copy, quiet = TRUE)red <- testthat::test_file(test_file, reporter = "silent")as_tibble(red) |> select(failed, error, passed)#> # A tibble: 1 x 3#> failed error passed#> <int> <lgl> <int>#> 1 0 TRUE 0
# 2. The code: a new check in step 010code_file <- file.path(copy, "R", "count_subj.R")code <- readLines(code_file)step_020 <- grep("# Step 020", code)check <- c( " by_cols <- try(dplyr::select(data, {{ by }}), silent = TRUE)", " if (inherits(by_cols, \"try-error\")) {", " cli::cli_abort(\"A column of {.arg by} is not in {.arg data}.\")", " }", "")writeLines(append(code, check, after = step_020 - 1), code_file)
pkgload::load_all(copy, quiet = TRUE)green <- testthat::test_file(test_file, reporter = "silent")as_tibble(green) |> select(failed, error, passed)#> # A tibble: 1 x 3#> failed error passed#> <int> <lgl> <int>#> 1 0 FALSE 1count_subj(pharmaverseadam::adae, ARMX) |> try()#> Error in count_subj(pharmaverseadam::adae, ARMX) :#> A column of `by` is not in `data`.The program works on a copy of the library. First the test: error is TRUE and passed is 0. The dplyr error does not match the expected message, so expect_error() passes the error on, and the test fails with an error. This is the “red” step. Then the program adds the check to step 010 and loads the library again: passed is 1, the “green” step. The last call shows the new message.
try(dplyr::select(data, {{ by }})) tests the by columns: select() fails when a column does not exist, and inherits(..., "try-error") sees that failure.
Exercise 19-2
Section titled “Exercise 19-2”# Answer 19-2: subjects with a percent of the big N, built on the librarylibrary(dplyr)pkgload::load_all("studylib", quiet = TRUE)
count_subj_pct <- function(data, adsl, by = TRT01A) { denom <- big_n(adsl, by = {{ by }}) count_subj(data, {{ by }}) |> left_join(denom, by = join_by({{ by }})) |> mutate(pct = round(100 * n_subj / N, 1))}
teae <- pharmaverseadam::adae |> filter(TRTEMFL == "Y")res <- count_subj_pct(teae, pharmaverseadam::adsl)res#> # A tibble: 3 x 4#> TRT01A n_subj N pct#> <chr> <int> <int> <dbl>#> 1 Placebo 65 86 75.6#> 2 Xanomeline High Dose 68 72 94.4#> 3 Xanomeline Low Dose 84 96 87.5
# The tests: silent when they passtestthat::expect_equal(res$pct[res$TRT01A == "Placebo"], 75.6)testthat::expect_true(all(res$n_subj <= res$N))75.6% of the placebo subjects (65 of 86) had a TEAE. The new function is built on the two functions of the library, not copied from them, so a fix in count_subj() reaches it too. The two expectations are silent: they pass.
Exercise 19-3
Section titled “Exercise 19-3”# Answer 19-3: a new function in the library: code, roxygen block, test# A session can still hold the library from an earlier program: unload it, so the new copy is the only oneif ("studylib" %in% loadedNamespaces()) pkgload::unload("studylib")
copy <- file.path(tempdir(), "studylib_x3")unlink(copy, recursive = TRUE)dir.create(copy)files <- list.files("studylib", full.names = TRUE)invisible(file.copy(files, copy, recursive = TRUE))
writeLines(c( "# n_pct.R: a count and its percent as one text, such as 65 (75.6)", "#", "# Change log:", "# 0.2.0 2026-11-19 First version.", "", "#' A count with its percent", "#'", "#' @param n The counts.", "#' @param total The totals, as many as `n` or one.", "#' @param digits The decimals of the percent. Default 1.", "#' @return A text vector, such as `\"65 (75.6)\"`.", "#' @examples", "#' n_pct(65, 86)", "#' @export", "n_pct <- function(n, total, digits = 1) {", " # Step 010: check the arguments", " if (!is.numeric(n) || !is.numeric(total) || any(total <= 0)) {", " cli::cli_abort(\"{.arg n} and {.arg total}: numbers, total > 0.\")", " }", " # Step 020: the text", " pct <- formatC(100 * n / total, format = \"f\", digits = digits)", " paste0(n, \" (\", pct, \")\")", "}"), file.path(copy, "R", "n_pct.R"))
writeLines(c( 'test_that("n_pct() writes the count and the percent", {', ' expect_equal(n_pct(65, 86), "65 (75.6)")', ' expect_equal(n_pct(c(1, 2), 4, digits = 0), c("1 (25)", "2 (50)"))', ' expect_error(n_pct(5, 0), "total > 0")', '})'), file.path(copy, "tests", "testthat", "test-n_pct.R"))
roxygen2::roxygenise(copy)#> i Loading studylib#> Writing 'NAMESPACE'#> Writing 'n_pct.Rd'readLines(file.path(copy, "NAMESPACE"))#> [1] "# Generated by roxygen2: do not edit by hand"#> [2] ""#> [3] "export(big_n)"#> [4] "export(count_subj)"#> [5] "export(n_pct)"
# test_local() runs the tests inside the package, so a function of the same name in your workspace# (chapter 13 made an n_pct() of its own) cannot hide the package's one (chapter 17: where R finds a name)res <- testthat::test_local(copy, reporter = "silent", stop_on_failure = FALSE)sum(as.data.frame(res)$failed)#> [1] 0studylib::n_pct(65, 86)#> [1] "65 (75.6)"roxygen2 writes n_pct.Rd, and NAMESPACE gets the line export(n_pct). test_local() loads the package and runs its tests inside it. All tests of the library pass (0 failed), the three new expectations too. studylib::n_pct(65, 86) gives "65 (75.6)", the cell of a table.
Why test_local() and studylib::? If your session already has an n_pct() of its own (program 13 made one that writes 65 (75.6%)), a plain n_pct() call finds that one first: the workspace comes before every attached package (chapter 17). In the DataStep Studio for R session, where the objects of every run stay, this happened: the tests found the old function and failed. Inside the package, and with package::, there is no doubt which function runs.
Exercise 19-4
Section titled “Exercise 19-4”# Answer 19-4: stop in count_subj(), go to step 030, look at subjcommands <- c( 'pkgload::load_all("studylib", quiet = TRUE)', 'teae <- dplyr::filter(pharmaverseadam::adae, TRTEMFL == "Y")', "debugonce(count_subj)", "count_subj(teae, TRT01A)", "n", "n", "n", "n", # the three checks of step 010 "n", # step 020 runs: now subj exists "nrow(subj)", "nrow(teae)", "c" # continue to the end)out <- system2( file.path(R.home("bin"), "R"), c("--vanilla", "--quiet"), input = commands, stdout = TRUE, stderr = TRUE, env = c(paste0("R_LIBS=", paste(.libPaths(), collapse = ":")), "LC_ALL=C"))out <- out[!grepl("built under R version|^Warning message:$", out)]# Only the prompts and what they print, not the code of each stepout <- gsub(getwd(), ".", out, fixed = TRUE)writeLines(grep("^(Browse|>)|^\\[1\\]|^debug at", out, value = TRUE))#> > pkgload::load_all("studylib", quiet = TRUE)#> > teae <- dplyr::filter(pharmaverseadam::adae, TRTEMFL == "Y")#> > debugonce(count_subj)#> > count_subj(teae, TRT01A)#> debug at ./studylib/R/count_subj.R#21: {#> Browse[1]> n#> debug at ./studylib/R/count_subj.R#23: if (!is.data.frame(data)) {#> Browse[1]> n#> debug at ./studylib/R/count_subj.R#28: if (!rlang::is_string(id)) {#> Browse[1]> n#> debug at ./studylib/R/count_subj.R#31: if (!id %in% names(data)) {#> Browse[1]> n#> debug at ./studylib/R/count_subj.R#39: subj <- dplyr::distinct(data, dplyr::pick({#> Browse[1]> n#> debug at ./studylib/R/count_subj.R#43: dplyr::count(subj, dplyr::pick({#> Browse[1]> nrow(subj)#> [1] 217#> Browse[1]> nrow(teae)#> [1] 1122#> Browse[1]> c#> >Five times n go past the three checks of step 010 and run step 020. At step 030, subj has 217 rows and teae has 1122. subj has one row per arm and subject, so 217 is the sum of the three counts (65, 68 and 84). The difference is the rule of chapter 1: 1122 records, 217 subjects.
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.