Build, test and debug a function library
A function that you use in one program is a shortcut. A function that the whole team uses is a product. Other people call it with input you did not expect, and a wrong number from it lands in every table of the study. This chapter builds a small study library the way experienced clinical programmers build theirs: each function with a header and checks, all functions in one package, every function with tests.
Chapter 8 wrote count_by() in a file that programs source(). That works for a few functions. A study with twenty functions needs more: help pages, tests that run with one call, and one place to load them from.
19.1 A library function
Section titled “19.1 A library function”Here is the first function of the library, count_subj(). It counts the subjects per group.
# count_subj.R: count the subjects per group## Change log:# 0.1.0 2026-11-19 First version.
#' Count the subjects per group#'#' Counts the distinct subjects of `data` for each combination of the `by`#' columns. A subject with many records counts once per group.#'#' @param data A data frame with one row per record, such as ADAE.#' @param by The columns to count by, without quotes: `TRT01A` or#' `c(TRT01A, AESEV)`.#' @param id The name of the subject column, as text. Default `"USUBJID"`.#' @return A tibble with the `by` columns and `n_subj`, one row per group,#' sorted by the `by` columns.#' @examples#' teae <- dplyr::filter(pharmaverseadam::adae, TRTEMFL == "Y")#' count_subj(teae, TRT01A)#' @exportcount_subj <- function(data, by, id = "USUBJID") { # Step 010: check the arguments before any work if (!is.data.frame(data)) { cli::cli_abort( "{.arg data} must be a data frame, not {.obj_type_friendly {data}}." ) } if (!rlang::is_string(id)) { cli::cli_abort("{.arg id} must be one text, such as {.val USUBJID}.") } if (!id %in% names(data)) { cli::cli_abort(c( "Column {.field {id}} is not in {.arg data}.", "i" = "Give the subject column with {.code id = \"...\"}." )) }
# Step 020: one row per group and subject subj <- data |> dplyr::distinct(dplyr::pick({{ by }}), .data[[id]])
# Step 030: count the subjects of each group subj |> dplyr::count(dplyr::pick({{ by }}), name = "n_subj")}Read it from top to bottom. Each part has a job:
- A change log at the top of the file, with a version and a date for every change. The next programmer sees what changed and when.
- A roxygen block: the lines that start with
#'. It is the header of the function: the purpose, every argument (@param), the result (@return) and a real call (@examples).@exportmakes the function visible to the users of the package. Section 19.5 turns the block into a help page. - Step 010 checks the arguments before any work. Each check stops with
cli::cli_abort()and a message that says what is wrong and how to fix it.{.arg data}and{.field {id}}format the names. - Numbered steps with comments: 020 makes one row per group and subject, 030 counts. A reviewer can follow the steps, and a new step fits in as 025.
dplyr::before every function. A package does not uselibrary(). It names the package of each function, so it works whatever the caller loaded.
19.2 A package: the skeleton of a library
Section titled “19.2 A package: the skeleton of a library”A package is a folder with a fixed layout. R knows how to load it, how to find its help pages and how to run its tests. The library of this chapter is in programs/studylib/:
| File or folder | What it holds |
|---|---|
DESCRIPTION |
the name, the version, the purpose, and the packages it needs |
R/ |
the functions, one file per function or per topic |
tests/testthat/ |
the tests, one file per function: test-count_subj.R |
NAMESPACE |
which functions the package exports; roxygen2 writes it |
man/ |
the help pages; roxygen2 writes them |
The DESCRIPTION file:
Package: studylibTitle: Functions of the CDISC Pilot StudyVersion: 0.1.0Authors@R: person("Study", "Programmer", role = c("aut", "cre"), email = "programmer@example.com")Description: Small functions that every table program of the study uses: count subjects per group, and the big N of a population.License: MITEncoding: UTF-8Imports: cli, dplyr, rlangSuggests: testthat (>= 3.0.0), pharmaverseadamConfig/testthat/edition: 3Config/roxygen2/version: 8.1.1Imports lists the packages that the functions use: cli, dplyr and rlang. Suggests lists the packages that only the tests and the examples need. Config/testthat/edition: 3 asks for the current rules of testthat.
pkgload::load_all() loads the package from its folder, without an installation. Every function of R/ is then ready to use:
# Chapter 19: load the study library with pkgload::load_all(), then use itlibrary(dplyr)pkgload::load_all("studylib")#> i Loading studylib
teae <- pharmaverseadam::adae |> filter(TRTEMFL == "Y")
count_subj(teae, TRT01A)#> # A tibble: 3 x 2#> TRT01A n_subj#> <chr> <int>#> 1 Placebo 65#> 2 Xanomeline High Dose 68#> 3 Xanomeline Low Dose 84count_subj(teae, c(TRT01A, AESEV)) |> print(n = 3)#> # A tibble: 9 x 3#> TRT01A AESEV n_subj#> <chr> <chr> <int>#> 1 Placebo MILD 58#> 2 Placebo MODERATE 25#> 3 Placebo SEVERE 5#> # i 6 more rowsbig_n(pharmaverseadam::adsl)#> # A tibble: 3 x 2#> TRT01A N#> <chr> <int>#> 1 Placebo 86#> 2 Xanomeline High Dose 72#> 3 Xanomeline Low Dose 96count_subj(teae, TRT01A)gives the subjects with at least one TEAE: 65 on placebo, 68 on the high dose and 84 on the low dose. These are actual arms (TRT01A): in the reference data, the actual arm differs from the planned arm for some subjects.- With two
bycolumns, the result has one row per arm and severity: 5 placebo subjects had a severe TEAE. big_n()is the second function of the library: the subjects of the safety population per arm, 86, 72 and 96.
Run load_all() again after each change to a file in R/. It loads the new version.
19.3 A clear error
Section titled “19.3 A clear error”A wrong call must stop at step 010, before any work, with a message for a person:
# Chapter 19: a wrong call stops at step 010, with a message that says what to fixpkgload::load_all("studylib", quiet = TRUE)
adae <- pharmaverseadam::adaecount_subj(adae, TRT01A, id = "SUBJECT")#> Error in `count_subj()`:#> ! Column SUBJECT is not in `data`.#> i Give the subject column with `id = "..."`.The error names the function (count_subj()), the problem (column SUBJECT is not in data) and the fix (id = "..."). Without the check, the error would come from deep inside dplyr::distinct() and name a column that the caller never thinks about.
19.4 Test it like a product
Section titled “19.4 Test it like a product”A test runs a function with known input and checks the result. The package testthat writes tests in a fixed form:
teae <- dplyr::filter(pharmaverseadam::adae, TRTEMFL == "Y")
test_that("count_subj() counts subjects, not records", { res <- count_subj(teae, TRT01A) expect_equal(res$n_subj, c(65, 68, 84)) expect_lt(sum(res$n_subj), nrow(teae))})
test_that("count_subj() gives one row per group", { res <- count_subj(teae, c(TRT01A, AESEV)) expect_equal(nrow(res), nrow(dplyr::distinct(teae, TRT01A, AESEV))) expect_named(res, c("TRT01A", "AESEV", "n_subj"))})
test_that("count_subj() follows 01-701-1015", { one <- dplyr::filter(teae, USUBJID == "01-701-1015") expect_equal(count_subj(one, TRT01A)$n_subj, 1)})
test_that("count_subj() stops with a clear message", { expect_error(count_subj("adae", TRT01A), "must be a data frame") expect_error(count_subj(teae, TRT01A, id = "SUBJ"), "is not in") expect_error(count_subj(teae, TRT01A, id = c("A", "B")), "one text")})
test_that("count_subj() gives no warning", { expect_no_warning(count_subj(teae, TRT01A))})test_that("what it does", { ... })is one test. Its name is a sentence that says what must be true.- An expectation checks one fact.
expect_equal(a, b)passes whenaandbare equal.expect_error(code, "text")passes when the code stops with an error whose message contains the text.expect_named(),expect_lt()andexpect_no_warning()check names, a smaller value and a clean run. - The first test checks the study numbers (65, 68, 84) and the rule of chapter 1: fewer subjects than records.
- A test for each check of step 010: a wrong call must give the right message.
testthat::test_dir() runs every test file of the folder:
# Chapter 19: run the tests of the library. Each expectation passes or failslibrary(dplyr)pkgload::load_all("studylib", quiet = TRUE)
res <- testthat::test_dir("studylib/tests/testthat", reporter = testthat::SummaryReporter$new(show_praise = FALSE))#> big_n: ..#> count_subj: .........#>#> == DONE ========================================================================
# The result as a table: one row per test_that(), nb = number of expectationsas_tibble(res) |> select(file, test, nb, failed)#> # A tibble: 7 x 4#> file test nb failed#> <chr> <chr> <int> <int>#> 1 test-big_n.R big_n() gives the safety population per arm 1 0#> 2 test-big_n.R big_n() refuses a data set with two rows for a~ 1 0#> 3 test-count_subj.R count_subj() counts subjects, not records 2 0#> 4 test-count_subj.R count_subj() gives one row per group 2 0#> 5 test-count_subj.R count_subj() follows 01-701-1015 1 0#> 6 test-count_subj.R count_subj() stops with a clear message 3 0#> 7 test-count_subj.R count_subj() gives no warning 1 0SummaryReporter$new(show_praise = FALSE) is the summary reporter without its random word of praise, so the output is the same at every run. It prints one dot per passed expectation: 2 for big_n(), 9 for count_subj(). A failure would print its number and, at the end, the test and the values that differ. The table shows the 7 tests: nb is the number of expectations of each test, and failed is 0 everywhere.
Run the tests after every change to the library. When a change breaks a case, you see it before your colleagues do. Write the test of a new rule first, see it fail, then write the code: exercise 19-1 shows this order.
19.5 Help pages with roxygen2
Section titled “19.5 Help pages with roxygen2”The #' lines are for roxygen2. roxygen2::roxygenise() reads them and writes two things: a help page for each function in man/, and the NAMESPACE file with one export() line for each @export. You never edit these files by hand. This program runs roxygen2 on a copy of the library, so that it writes every file again:
# Chapter 19: roxygen2 writes NAMESPACE and the help pages from the #' comments# Work on a copy in a temporary folder, so that the run writes every file anewcopy <- file.path(tempdir(), "studylib")unlink(copy, recursive = TRUE)invisible(file.copy("studylib", tempdir(), recursive = TRUE))unlink(file.path(copy, c("NAMESPACE", "man")), recursive = TRUE)
roxygen2::roxygenise(copy)#> i Loading studylib#> Writing 'NAMESPACE'#> Writing 'big_n.Rd'#> Writing 'count_subj.Rd'
list.files(copy, recursive = TRUE)#> [1] "DESCRIPTION" "man/big_n.Rd"#> [3] "man/count_subj.Rd" "NAMESPACE"#> [5] "R/big_n.R" "R/count_subj.R"#> [7] "tests/testthat.R" "tests/testthat/test-big_n.R"#> [9] "tests/testthat/test-count_subj.R"readLines(file.path(copy, "NAMESPACE"))#> [1] "# Generated by roxygen2: do not edit by hand"#> [2] ""#> [3] "export(big_n)"#> [4] "export(count_subj)"- Writing ‘count_subj.Rd’: the help page of
count_subj(). Afterload_all(),?count_subjshows it, with the arguments, the result and the example of the roxygen block. NAMESPACEexportsbig_nandcount_subj. A function without@exportstays inside the package: the other functions can use it, a program cannot. Use this for a small helper that only the library needs.list.files(recursive = TRUE)shows the whole skeleton: 9 files.
Run roxygenise() after every change to a #' block. The header and the help page then cannot disagree.
19.6 Debug a function
Section titled “19.6 Debug a function”A function gives a wrong value, and you want to look inside while it runs. debugonce(f) marks the function f: the next call stops at its first line, and you can run it line by line. Here is such a session. The program types the commands for you, so that the page shows a real session:
# Chapter 19: a debug session with debugonce(). R reads the commands from a# script, line by line, as if you typed them at the consolecommands <- c( 'pkgload::load_all("studylib", quiet = TRUE)', "debugonce(big_n)", "big_n(pharmaverseadam::adsl)", "ls()", # the arguments of big_n() "pop", "n", # the next step "n", "nrow(adsl)", "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"))# Leave out the notes of this machine about package builds; short pathsout <- out[!grepl("built under R version|^Warning message:$", out)]writeLines(gsub(getwd(), ".", out, fixed = TRUE))#> > pkgload::load_all("studylib", quiet = TRUE)#> > debugonce(big_n)#> > big_n(pharmaverseadam::adsl)#> debugging in: big_n(pharmaverseadam::adsl)#> debug at ./studylib/R/big_n.R#17: {#> if (!pop %in% names(adsl)) {#> cli::cli_abort("Column {.field {pop}} is not in {.arg adsl}.")#> }#> if (anyDuplicated(adsl$USUBJID) > 0) {#> cli::cli_abort("{.arg adsl} must have one row per subject.")#> }#> dplyr::count(dplyr::filter(adsl, .data[[pop]] == "Y"), {#> {#> by#> }#> }, name = "N")#> }#> Browse[1]> ls()#> [1] "adsl" "by" "pop"#> Browse[1]> pop#> [1] "SAFFL"#> Browse[1]> n#> debug at ./studylib/R/big_n.R#19: if (!pop %in% names(adsl)) {#> cli::cli_abort("Column {.field {pop}} is not in {.arg adsl}.")#> }#> Browse[1]> n#> debug at ./studylib/R/big_n.R#22: if (anyDuplicated(adsl$USUBJID) > 0) {#> cli::cli_abort("{.arg adsl} must have one row per subject.")#> }#> Browse[1]> nrow(adsl)#> [1] 306#> Browse[1]> c#> exiting from: big_n(pharmaverseadam::adsl)#> # A tibble: 3 x 2#> TRT01A N#> <chr> <int>#> 1 Placebo 86#> 2 Xanomeline High Dose 72#> 3 Xanomeline Low Dose 96#> >debugonce(big_n), then the call. R prints the code of the function and the promptBrowse[1]>. You are inside the function now.ls()shows the names of the function: its argumentsadsl,byandpop.popshows the value of one:"SAFFL". Any R code works here:nrow(adsl)is 306, all subjects of the reference ADSL.nruns the next line. debug at ./studylib/R/big_n.R#22 says where you are: file and line.ccontinues to the end, and the function returns its result as usual.
Command at Browse[1]> |
What it does |
|---|---|
n |
run the next line |
s |
step into the function that the line calls |
f |
finish the current loop or function |
c |
continue to the end, or to the next stop |
Q |
quit the debugger |
where |
show the calls that led here |
debugonce() stops once. debug(f) stops at every call until undebug(f). To stop at one line, write browser() on that line in the code, run load_all(), and call the function. Remove the browser() line when you are done.
19.7 Design a function: the checklist
Section titled “19.7 Design a function: the checklist”Ten rules make a good study function. They make a function easy to call, easy to check and easy to debug a year later. Use them as a checklist for every function of the library.
| # | Rule | Where you see it |
|---|---|---|
| 1 | The header is the contract. A roxygen block with the purpose, every argument, the result and a real example. | count_subj() |
| 2 | A change log with a version and a date for every change. | the top of each file in R/ |
| 3 | Check first, then work. Step 010 stops a wrong call with cli::cli_abort(), before any work. |
count_subj(), big_n() |
| 4 | Messages for a person. Say what is wrong and how to fix it; name the argument with {.arg}. |
19.3 |
| 5 | Numbered steps with comments, in the order of the specification. | count_subj() |
| 6 | Every input is an argument. A function never reads a variable of the program (chapter 17). | big_n(pop = "SAFFL") |
| 7 | Safe defaults. The default is the usual case of the study: the safety population, the actual arm. | big_n() |
| 8 | Name the package of every function: dplyr::filter(). |
every file in R/ |
| 9 | Export only what programs call. Helpers stay inside the package. | NAMESPACE |
| 10 | A test for every rule and every check. Write the test first. | tests/testthat/ |
The template
Section titled “The template”Copy this skeleton for every new function, then fill in the parts in angle brackets:
# <name>.R: <one line: what the function does>## Change log:# 0.1.0 <date> First version.
#' <A title in a few words>#'#' <One or two sentences: what the function does.>#'#' @param data <What it is, for example ADSL.>#' @param by <The columns, without quotes.>#' @return <What comes back: a tibble with ... .>#' @examples#' <a real call on pharmaverseadam data>#' @export<name> <- function(data, by) { # Step 010: check the arguments if (!is.data.frame(data)) { cli::cli_abort("{.arg data} must be a data frame.") }
# Step 020: <the first step>
# Step 030: <the result>}Then add tests/testthat/test-<name>.R, run roxygen2::roxygenise(), pkgload::load_all() and testthat::test_dir().
19.8 Summary
Section titled “19.8 Summary”- A library function has a change log, a roxygen header, checks in step 010 with
cli::cli_abort(), and numbered steps. - A package is a folder:
DESCRIPTION,R/,tests/testthat/, andNAMESPACEandman/that roxygen2 writes. pkgload::load_all()loads the package from its folder. Run it after each change.test_that()withexpect_equal(),expect_error()andexpect_no_warning()writes a test.testthat::test_dir()runs them all.roxygen2::roxygenise()writes the help pages and the exports from the#'comments.debugonce()andbrowser()stop inside a function:n,s,c,Q.
19.9 Exercises
Section titled “19.9 Exercises”Exercise 19-1. count_subj(adae, ARMX) stops with an error from inside dplyr. Write a test first: the call must stop with the message “A column of by is not in data”. See it fail. Then add the check to step 010, and see the test pass.
Exercise 19-2. Write count_subj_pct(data, adsl, by). It adds N from big_n() and pct, the percent of N. What percent of the placebo subjects had a TEAE? Check it with an expectation.
Exercise 19-3. Add a third function to the library: n_pct(n, total, digits = 1) gives a text such as "65 (75.6)". Write the file with a change log and a roxygen block, write a test file, run roxygenise() and the tests. Which line does NAMESPACE get?
Exercise 19-4. Debug count_subj(teae, TRT01A) with debugonce(). Go with n to step 030. How many rows does subj have, and how many rows does teae have? What does the difference mean?
The answers are in Answers, Parts IV and V.
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.