Functions
You have used many functions already: filter(), count(), mean(). Now you write your own. A function is a named piece of code that takes inputs and gives back a result. When you need the same steps three times, write them once as a function. Then a fix is one change, not three, and every table of the study counts the same way.
8.1 Write a function
Section titled “8.1 Write a function”# Chapter 8: a function has a name, arguments with defaults and a return valuepct <- function(n, total, digits = 1) { round(100 * n / total, digits)}
pct(65, 86)#> [1] 75.6pct(65, 86, digits = 2)#> [1] 75.58pct(n = c(65, 68, 84), total = c(86, 72, 96))#> [1] 75.6 94.4 87.5
# return() ends the function early; otherwise the last value is returnedpct_or_na <- function(n, total, digits = 1) { if (total == 0) { return(NA_real_) } round(100 * n / total, digits)}pct_or_na(0, 0)#> [1] NApct_or_na(65, 86)#> [1] 75.6pct <- function(n, total, digits = 1) { ... }makes a function and stores it under the namepct, like any other value.n,totalanddigitsare its arguments: the inputs.digits = 1is a default: the value that the argument has when the caller does not give one.- The code between
{and}is the body. The value of its last line is the return value: what the function gives back. - You call the function with values for its arguments.
pct(65, 86)gives 75.6: 65 of 86 placebo subjects had a TEAE (chapter 6).pct(65, 86, digits = 2)changes the default and gives 75.58. - The body is vectorised, so the function is too. Three counts and three totals give three percents in one call.
return() ends a function at once and gives back its value. pct_or_na() uses it to stop early when the total is 0. Without return(), the last value of the body is the result.
Arguments can be given by position (pct(65, 86)) or by name (pct(n = 65, total = 86)). Use names for every argument after the first two: the call then explains itself.
8.2 A column as an argument: embracing
Section titled “8.2 A column as an argument: embracing”A clinical function usually takes a data frame and the name of a column. Here is one that counts any column, with percents.
# Chapter 8: {{ }} passes a column name from the caller to a dplyr verblibrary(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, SEX)#> # A tibble: 2 x 3#> SEX n pct#> <chr> <int> <dbl>#> 1 F 143 56.3#> 2 M 111 43.7freq_one(adsl, RACE)#> # A tibble: 3 x 3#> RACE n pct#> <chr> <int> <dbl>#> 1 AMERICAN INDIAN OR ALASKA NATIVE 1 0.4#> 2 BLACK OR AFRICAN AMERICAN 23 9.1#> 3 WHITE 230 90.6freq_one(adsl |> filter(TRT01A == "Placebo"), SEX)#> # A tibble: 2 x 3#> SEX n pct#> <chr> <int> <dbl>#> 1 F 53 61.6#> 2 M 33 38.4{{ var }} is called embracing. It says to count(): “use the column that the caller named”. The caller writes SEX without quotes, as in any dplyr call. One function now counts SEX, RACE, or the sex of the placebo arm only: 53 women, 61.6%.
This is tidy evaluation: dplyr looks for column names inside the data frame first. A function argument is outside the data frame, so you must tell dplyr to look through it. {{ }} does that.
8.3 What happens without the braces
Section titled “8.3 What happens without the braces”# Chapter 8: without {{ }}, count() looks for a column named varlibrary(dplyr)
freq_bad <- function(data, var) { data |> count(var) |> mutate(pct = round(100 * n / sum(n), 1))}
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")freq_bad(adsl, SEX)#> Error in `count()` at dplyr/R/mutate.R:146:3:#> ! Must group by variables found in `.data`.#> x Column `var` is not found.Without the braces, count(var) looks for a column with the name var. The data frame has none, and the error says so: Column var is not found. When a function of yours gives this error with the name of an argument, a pair of braces is missing.
Chapter 17 explains tidy evaluation in depth. For daily work, two rules are enough: embrace a bare column name with {{ }}, and use .data[[ ]] for a name in a text.
8.4 A column name in a text: the .data pronoun
Section titled “8.4 A column name in a text: the .data pronoun”Sometimes the column name is a text value: it comes from a list, a specification or a file. Then use .data[[var]].
# Chapter 8: .data[[ ]] uses a column whose name is in a text valuelibrary(dplyr)
freq_chr <- function(data, var) { data |> count(.data[[var]]) |> mutate(pct = round(100 * n / sum(n), 1))}
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")freq_chr(adsl, "SEX")#> # A tibble: 2 x 3#> SEX n pct#> <chr> <int> <dbl>#> 1 F 143 56.3#> 2 M 111 43.7
# the names can come from data, so a loop can give them one by onefor (v in c("SEX", "ETHNIC")) { print(freq_chr(adsl, v))}#> # A tibble: 2 x 3#> SEX n pct#> <chr> <int> <dbl>#> 1 F 143 56.3#> 2 M 111 43.7#> # A tibble: 2 x 3#> ETHNIC n pct#> <chr> <int> <dbl>#> 1 HISPANIC OR LATINO 12 4.7#> 2 NOT HISPANIC OR LATINO 242 95.3.datais the data frame that the verb works on..data[["SEX"]]is its columnSEX.- The caller now gives
"SEX"in quotes. The output is the same as with{{ }}. - Because the names are text, a
forloop can give them one by one. Inside a loop,print()is needed to show a result.
| The caller writes | In the function | Example |
|---|---|---|
a bare name: SEX |
{{ var }} |
count({{ var }}) |
a text: "SEX" |
.data[[var]] |
count(.data[[var]]) |
8.5 A function written the professional way
Section titled “8.5 A function written the professional way”A function that others use must explain itself, check its input, and stop with a clear message when the call is wrong. Keep such functions in their own file. This file holds one function, count_by():
# count_by.R: count subjects and records per group## Purpose: Count the subjects (distinct values of `id`) and the records of a# data frame, for each combination of the columns in `by`.# Arguments: data A data frame, for example pharmaverseadam::adae.# by The columns to count by, without quotes: c(TRT01A, AESEV).# id The name of the subject column, as text. Default "USUBJID".# Returns: A tibble with the `by` columns, n_subj and n_rec: one row per group.# Example: count_by(pharmaverseadam::adae, c(TRT01A, AESEV))# Change log:# 1.0 2026-11-19 First version.# 1.1 2026-11-19 Checks of data and id, with clear messages.
count_by <- function(data, by, id = "USUBJID") { stopifnot(is.character(id), length(id) == 1) if (!is.data.frame(data)) { cli::cli_abort("{.arg data} must be a data frame, not {.obj_type_friendly {data}}.") } 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 = \"...\"}." )) }
data |> dplyr::group_by(dplyr::pick({{ by }})) |> dplyr::summarise( n_subj = dplyr::n_distinct(.data[[id]]), n_rec = dplyr::n(), .groups = "drop" )}The habits in this file, one by one:
- A header that a reader can use without reading the code: purpose, every argument, the return value, an example, and a change log with versions.
stopifnot()checks conditions that must be true. If one is false, it stops with a short message. Use it for mistakes of the programmer, such as a number where a text belongs.cli::cli_abort()stops with a message for a person.{.arg data}and{.field {id}}format the names. The"i"line tells the reader what to do.dplyr::before each function. The file then works whatever packages the caller loaded.pick({{ by }})lets the caller give one column or several:TRT01Aorc(TRT01A, AESEV).
source() runs a file of R code. The functions in it are then ready to use:
# Chapter 8: source() a file of functions, then call onelibrary(dplyr)source("R/count_by.R")
teae <- pharmaverseadam::adae |> filter(SAFFL == "Y", TRTEMFL == "Y")
count_by(teae, TRT01A)#> # A tibble: 3 x 3#> TRT01A n_subj n_rec#> <chr> <int> <int>#> 1 Placebo 65 281#> 2 Xanomeline High Dose 68 414#> 3 Xanomeline Low Dose 84 427count_by(teae, c(TRT01A, AESEV))#> # A tibble: 9 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 6#> 4 Xanomeline High Dose MILD 64 286#> 5 Xanomeline High Dose MODERATE 46 118#> 6 Xanomeline High Dose SEVERE 8 10#> 7 Xanomeline Low Dose MILD 64 232#> 8 Xanomeline Low Dose MODERATE 58 170#> 9 Xanomeline Low Dose SEVERE 16 25count_by(teae |> filter(USUBJID == "01-701-1015"), AESOC)#> # A tibble: 2 x 3#> AESOC n_subj n_rec#> <chr> <int> <int>#> 1 GASTROINTESTINAL DISORDERS 1 1#> 2 GENERAL DISORDERS AND ADMINISTRATION SITE CONDITIONS 1 2The first call gives the subjects and records per arm: 65 subjects and 281 records on placebo. The last call follows 01-701-1015: 1 subject and 2 records in one SOC, as in chapter 6.
A wrong call stops before any work, with a message that says what to fix:
# Chapter 8: a wrong call stops with a message that says what to fixlibrary(dplyr)source("R/count_by.R")
dm <- pharmaversesdtm::dm |> rename(SUBJECT = USUBJID)count_by(dm, ARM)#> Error in `count_by()`:#> ! Column USUBJID is not in `data`.#> i Give the subject column with `id = "..."`.The error names the function (count_by()), the problem (column USUBJID is not in data) and the fix (id = "..."). Compare it with the error of 08_3: that one came from deep inside count() and named a column that the caller never wrote.
8.6 Loop over a list: map() and walk()
Section titled “8.6 Loop over a list: map() and walk()”A list is an R value that holds other values of any kind: numbers, texts, whole data frames. map() from the purrr package calls a function once for each element of a list or a vector, and gives back a list of the results.
# Chapter 8: map() calls a function for each element of a listlibrary(dplyr)library(purrr)
adsl <- pharmaverseadam::adsl |> filter(SAFFL == "Y")
one_var <- function(var) { adsl |> count(VALUE = .data[[var]]) |> mutate(VARIABLE = var, .before = 1)}
tables <- map(c("SEX", "RACE", "ETHNIC"), one_var)length(tables)#> [1] 3tables[[1]]#> # A tibble: 2 x 3#> VARIABLE VALUE n#> <chr> <chr> <int>#> 1 SEX F 143#> 2 SEX M 111
# stack the results into one data framelist_rbind(tables)#> # A tibble: 7 x 3#> VARIABLE VALUE n#> <chr> <chr> <int>#> 1 SEX F 143#> 2 SEX M 111#> 3 RACE AMERICAN INDIAN OR ALASKA NATIVE 1#> 4 RACE BLACK OR AFRICAN AMERICAN 23#> 5 RACE WHITE 230#> 6 ETHNIC HISPANIC OR LATINO 12#> 7 ETHNIC NOT HISPANIC OR LATINO 242
# map_dfr() does map() and the stacking in one call (an older form)nrow(map_dfr(c("SEX", "RACE", "ETHNIC"), one_var))#> [1] 7
# walk() is for the side effect only, here a printed linewalk(c("SEX", "RACE", "ETHNIC"), \(v) cat(v, "has", n_distinct(adsl[[v]]), "values\n"))#> SEX has 2 values#> RACE has 3 values#> ETHNIC has 2 valuesmap(c("SEX", "RACE", "ETHNIC"), one_var)callsone_var("SEX"), thenone_var("RACE"), thenone_var("ETHNIC"). The result is a list of 3 data frames.tables[[1]]is the first one.list_rbind()stacks a list of data frames into one, likebind_rows(). The 7 rows are the start of a demographics table.map_dfr()doesmap()and the stacking in one call. You see it in older code.map()withlist_rbind()is the current form.walk()calls the function for its side effect only, here a printed line. It gives back nothing that you need.\(v) cat(...)is a short way to write a small function in place:\(v)is short forfunction(v).
| You want | Use |
|---|---|
| a list of results | map() |
| one data frame from many | map() then list_rbind() |
| a side effect: print, write a file | walk(), or a for loop |
A for loop can do all of this too. map() is shorter when you want the results back, because you need no empty list to fill.
8.7 A function for a build log
Section titled “8.7 A function for a build log”A study runs many programs in order. A build log is a text file with one line per step: what ran, and how many rows came out. When a number changes, the log shows where.
# Chapter 8: a function that writes one line of a build loglibrary(dplyr)
log_line <- function(file, program, step, data) { line <- sprintf("%-10s %-18s rows=%5d cols=%3d", program, step, nrow(data), ncol(data)) cat(line, "\n", sep = "", file = file, append = TRUE) invisible(line)}
log_file <- tempfile(fileext = ".log")
adsl <- pharmaverseadam::adsllog_line(log_file, "adsl.R", "read ADSL", adsl)
saf <- adsl |> filter(SAFFL == "Y")log_line(log_file, "adsl.R", "safety population", saf)
out <- saf |> select(USUBJID, TRT01A, AGE, SEX)log_line(log_file, "adsl.R", "keep 4 columns", out)
readLines(log_file)#> [1] "adsl.R read ADSL rows= 306 cols= 57"#> [2] "adsl.R safety population rows= 254 cols= 57"#> [3] "adsl.R keep 4 columns rows= 254 cols= 4"sprintf()puts values into a text template.%-10sis a text, left aligned, 10 characters wide.%5dis a whole number, 5 characters wide.cat(..., file = file, append = TRUE)adds the line at the end of the file.tempfile()gives a file name in a temporary folder, so this example leaves nothing behind.invisible(line)returns the line without printing it. The call is quiet, but the caller can still store the value.- The log shows the rows of each step: 306 in ADSL, 254 in the safety population.
8.8 Summary
Section titled “8.8 Summary”function(args) { body }makes a function. Defaults make arguments optional. The last value is the return value.{{ var }}passes a bare column name to a dplyr verb..data[[var]]uses a name in a text.- Check the arguments first:
stopifnot()for the programmer,cli::cli_abort()for a clear message to a person. - Give every shared function a header: purpose, arguments, returns, example, change log.
source()a file of functions. Usedplyr::inside it.map()loops and returns a list,list_rbind()stacks it,walk()is for side effects.
8.9 Exercises
Section titled “8.9 Exercises”Exercise 8-1. Write a function age_group(age) that gives "<65", "65-80", ">80" or "Missing". Check that age is a number. Use it inside mutate() on the safety population and count the groups.
Exercise 8-2. Use freq_one() of program 08_2 on the female subjects of the safety population only, to count RACE. How many women are White?
Exercise 8-3. Add stopifnot(is.numeric(n), is.numeric(total), total > 0) to pct(). What does pct(5, 0) give now?
Exercise 8-4. Call count_by() on the placebo TEAEs, by c(TRT01A, AESEV). How many placebo subjects had a severe TEAE, and how many severe records were there?
Exercise 8-5. Use map() over the three arms to compute n and the mean age of each arm, and stack the results. Check with all.equal() that the result is the same as group_by() with summarise().
The answers are in Answers, Part I (chapters 5 to 8).
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.