Skip to content

Tables by hand, then with packages

Part III turns analysis data into the outputs that a study delivers: tables, listings and figures (TLF). This chapter makes the two tables that every study has: demographics and adverse events. You build each table twice. First by hand, with the dplyr and tidyr functions that you know, so that you see where every number comes from. Then with the packages that the industry uses, gtsummary and rtables. At the end, a program proves that both ways give the same text in every cell.

All programs read the reference data of pharmaverseadam, so Part III runs on its own. The ADaM data sets that you build in Part II can take their place later.

A summary table looks simple: rows of statistics, one column per treatment. Behind it are four jobs, always in this order:

  1. Population and big N. Which subjects, and how many in each column. The big N is the number of subjects in a column. The header says Placebo (N=86), and every percent in that column divides by 86.
  2. Compute the statistics: n, mean and median for numbers, counts and percents for categories.
  3. Arrange them in a layout: a data frame with one row per printed line and one column per treatment. Every number in it is already text, formatted as the shell asks.
  4. Print the layout: on the screen, in an HTML page or in a Word file.

The shell is the mock table from the statistician. It shows the rows, the columns and the decimals, without numbers. Keep the four jobs apart. When a reviewer questions a number, look at job 2. When the shell changes the order of the rows, change job 3. When the page changes, change job 4, and no number moves.

The first job, in a program of its own:

programs/13_1_bign.R
# Chapter 13: the big N, the number of subjects in each column of a table
library(dplyr)
saf <- pharmaverseadam::adsl |>
filter(SAFFL == "Y")
# randomised to one arm, treated with another: 12 subjects
saf |>
count(ARM, TRT01A)
#> # A tibble: 4 x 3
#> ARM TRT01A n
#> <chr> <chr> <int>
#> 1 Placebo Placebo 86
#> 2 Xanomeline High Dose Xanomeline High Dose 72
#> 3 Xanomeline High Dose Xanomeline Low Dose 12
#> 4 Xanomeline Low Dose Xanomeline Low Dose 84
# the columns of the table: short names for the actual treatments, and a Total
cols <- c(
"Placebo" = "Placebo",
"Low Dose" = "Xanomeline Low Dose",
"High Dose" = "Xanomeline High Dose",
"Total" = "Total"
)
# Total: every subject a second time, with the treatment "Total"
adsl <- bind_rows(saf, mutate(saf, TRT01A = "Total")) |>
mutate(TRT = factor(TRT01A, levels = cols, labels = names(cols)))
bign <- adsl |>
count(TRT, name = "N") |>
mutate(header = paste0(TRT, " (N=", N, ")"))
bign
#> # A tibble: 4 x 3
#> TRT N header
#> <fct> <int> <chr>
#> 1 Placebo 86 Placebo (N=86)
#> 2 Low Dose 96 Low Dose (N=96)
#> 3 High Dose 72 High Dose (N=72)
#> 4 Total 254 Total (N=254)
adsl |>
filter(USUBJID == "01-701-1015") |>
select(USUBJID, ARM, TRT01A, TRT)
#> # A tibble: 2 x 4
#> USUBJID ARM TRT01A TRT
#> <chr> <chr> <chr> <fct>
#> 1 01-701-1015 Placebo Placebo Placebo
#> 2 01-701-1015 Placebo Total Total
  • The first count shows why a table must name its treatment variable. 12 subjects were randomised to the high dose (ARM) but received the low dose (TRT01A). A safety table counts by the actual treatment, so the columns hold 86, 96 and 72 subjects. Chapter 6 has the details.
  • cols is a named vector. Its values are the values of TRT01A. Its names are the short column titles.
  • The Total column is a trick. bind_rows() stacks the data on itself, and the second copy says TRT01A = "Total". Every later step counts the Total column like any other column, with no extra code.
  • factor(..., levels = cols, labels = names(cols)) fixes the order of the columns: placebo, low dose, high dose, Total. Text would sort them alphabetically (chapter 7).

Subject 01-701-1015 is now in the data twice: once as Placebo and once as Total.

programs/13_2_demog_hand.R
# Chapter 13: a demographics table by hand: big N, compute, arrange, print
library(dplyr)
library(tidyr)
round_half_up <- function(x, digits = 0) {
scale <- 10^digits
sign(x) * floor(abs(x) * scale + 0.5 + 1e-9) / scale
}
n_pct <- function(n, N) sprintf("%d (%.1f%%)", n, round_half_up(100 * n / N, 1))
# 1. population and big N (as in 13_1)
cols <- c(
"Placebo" = "Placebo", "Low Dose" = "Xanomeline Low Dose",
"High Dose" = "Xanomeline High Dose", "Total" = "Total"
)
saf <- pharmaverseadam::adsl |> filter(SAFFL == "Y")
adsl <- bind_rows(saf, mutate(saf, TRT01A = "Total")) |>
mutate(TRT = factor(TRT01A, levels = cols, labels = names(cols)))
bign <- count(adsl, TRT, name = "N")
# 2. compute: age, four lines of text per column
age <- adsl |>
group_by(TRT) |>
summarise(
n = as.character(n()),
`Mean (SD)` = sprintf(
"%.1f (%.2f)", round_half_up(mean(AGE), 1), round_half_up(sd(AGE), 2)
),
Median = sprintf("%.1f", round_half_up(median(AGE), 1)),
`Min, Max` = paste0(min(AGE), ", ", max(AGE))
) |>
pivot_longer(-TRT, names_to = "label", values_to = "value") |>
mutate(section = "Age (years)")
# 2. compute: age group, sex and race, subjects per value, percent of big N
# (factors give the order of the lines: text would sort ">64" before "18-64")
cats <- adsl |>
transmute(
TRT,
`Age group` = factor(AGEGR1, c("18-64", ">64")),
Sex = factor(SEX), Race = factor(RACE)
) |>
pivot_longer(-TRT, names_to = "section", values_to = "label") |>
count(TRT, section, label) |>
complete(TRT, nesting(section, label), fill = list(n = 0)) |>
left_join(bign, by = "TRT") |>
mutate(value = n_pct(n, N))
# 3. arrange: one row per printed line, one column per treatment
layout <- bind_rows(age, cats) |>
select(section, label, TRT, value) |>
mutate(label = as.character(label)) |>
pivot_wider(names_from = TRT, values_from = value) |>
arrange(factor(section, c("Age (years)", "Age group", "Sex", "Race")))
saveRDS(layout, "output/t_demog.rds")
# 4. print: a heading line per section, the other lines indented
options(width = 90) # the table is 83 characters wide: keep it on one line
sections <- distinct(layout, section) |> mutate(label = section)
bind_rows(sections, mutate(layout, label = paste0(" ", label))) |>
arrange(factor(section, unique(layout$section))) |>
select(-section) |>
as.data.frame() |>
print(na.print = "", right = FALSE, row.names = FALSE)
#> label Placebo Low Dose High Dose Total
#> Age (years)
#> n 86 96 72 254
#> Mean (SD) 75.2 (8.59) 76.0 (8.11) 73.8 (7.94) 75.1 (8.25)
#> Median 76.0 78.0 75.5 77.0
#> Min, Max 52, 89 51, 88 56, 88 51, 89
#> Age group
#> 18-64 14 (16.3%) 8 (8.3%) 11 (15.3%) 33 (13.0%)
#> >64 72 (83.7%) 88 (91.7%) 61 (84.7%) 221 (87.0%)
#> Sex
#> F 53 (61.6%) 55 (57.3%) 35 (48.6%) 143 (56.3%)
#> M 33 (38.4%) 41 (42.7%) 37 (51.4%) 111 (43.7%)
#> Race
#> AMERICAN INDIAN OR ALASKA NATIVE 0 (0.0%) 0 (0.0%) 1 (1.4%) 1 (0.4%)
#> BLACK OR AFRICAN AMERICAN 8 (9.3%) 6 (6.3%) 9 (12.5%) 23 (9.1%)
#> WHITE 78 (90.7%) 90 (93.8%) 62 (86.1%) 230 (90.6%)

The program has the four jobs as numbered comments. Read it step by step:

  • Two helpers. round_half_up() is the rounding function of chapter 3. n_pct() makes the text of a count cell: 53 (61.6%). Each cell of the study goes through the same two functions, so each cell has the same rounding and layout.
  • Age. summarise() makes one row per column, and each statistic is already text. The shell asks for one decimal more than the collected value for the mean and the median, and two more for the SD. pivot_longer() then turns the four statistics into four rows (chapter 7).
  • Categories. pivot_longer() puts age group, sex and race into one pair of columns, section and label. So one count() counts all three sections. The percent divides by the big N, not by the number of non-missing values: a subject with a missing value still counts in the denominator.
  • Factors give the order of the lines. As text, ">64" sorts before "18-64". The factor says which line comes first.
  • complete() makes the grid. Nobody on placebo is American Indian or Alaska Native, so count() makes no row for that cell. complete() adds every missing combination of column and line with n = 0. Without it, the cell would be empty, and an empty cell is not a 0.
  • Arrange. pivot_wider() turns the column TRT into four columns, one per treatment (chapter 7). saveRDS() keeps the layout for the comparison in 13.7.
  • Print. A heading line per section, the other lines indented by two blanks. na.print = "" prints the empty cells of the heading lines as blanks.

Read it before you send it. Each section adds up to the big N: 78 + 8 + 0 = 86 for race on placebo. The Total column is the sum of the three others: 53 + 55 + 35 = 143 women. And the American Indian line shows 0 (0.0%) on placebo, not a blank.

Exercise 13-1. Add ethnicity (ETHNIC) as a section. How many Hispanic or Latino subjects are in each column?

One cell of the demographics table shows why the helper round_half_up() is there. 6 of the 96 subjects in the low dose column are Black or African American:

programs/13_3_rounding.R
# Chapter 13: why a table program needs its own rounding function
round_half_up <- function(x, digits = 0) {
scale <- 10^digits
sign(x) * floor(abs(x) * scale + 0.5 + 1e-9) / scale
}
# 6 black subjects in the low dose column, N = 96
pct <- 100 * 6 / 96
pct
#> [1] 6.25
round(pct, 1)
#> [1] 6.2
sprintf("%.1f", pct)
#> [1] "6.2"
round_half_up(pct, 1)
#> [1] 6.3

The percent is exactly 6.25. round() and sprintf() both give 6.2, because R rounds a value exactly halfway to the even digit. A clinical table rounds it up: 6.3. If one programmer of a table uses round() and the second uses a round-half-up function, their tables differ in this one cell.

Exercise 13-4. Find every percent of the demographics table where round() and round_half_up() give different text.

13.4 Count subjects, not records: the adverse event table

Section titled “13.4 Count subjects, not records: the adverse event table”

ADAE has one record per adverse event, and a subject can have many. The table counts subjects: how many subjects had at least one headache. It has three levels:

  • System organ class (SOC, AEBODSYS): the body system of the event in the MedDRA dictionary, for example CARDIAC DISORDERS.
  • Preferred term (PT, AEDECOD): the standard name of the event, for example ATRIAL FIBRILLATION.
  • The first line: subjects with at least one treatment-emergent adverse event (TEAE).
programs/13_4_ae_hand.R
# Chapter 13: an adverse event table by hand: subjects per SOC and PT
library(dplyr)
library(tidyr)
round_half_up <- function(x, digits = 0) {
scale <- 10^digits
sign(x) * floor(abs(x) * scale + 0.5 + 1e-9) / scale
}
n_pct <- function(n, N) sprintf("%d (%.1f%%)", n, round_half_up(100 * n / N, 1))
cols <- c(
"Placebo" = "Placebo", "Low Dose" = "Xanomeline Low Dose",
"High Dose" = "Xanomeline High Dose", "Total" = "Total"
)
with_total <- function(data) {
bind_rows(data, mutate(data, TRT01A = "Total")) |>
mutate(TRT = factor(TRT01A, levels = cols, labels = names(cols)))
}
bign <- pharmaverseadam::adsl |>
filter(SAFFL == "Y") |>
with_total() |>
count(TRT, name = "N")
teae <- pharmaverseadam::adae |>
filter(SAFFL == "Y", TRTEMFL == "Y") |>
with_total()
# three levels, three counts of subjects: any TEAE, per SOC, per SOC and PT
any <- teae |>
distinct(TRT, USUBJID) |>
count(TRT)
soc <- teae |>
distinct(TRT, AEBODSYS, USUBJID) |>
count(TRT, AEBODSYS)
pt <- teae |>
distinct(TRT, AEBODSYS, AEDECOD, USUBJID) |>
count(TRT, AEBODSYS, AEDECOD)
# the order: most subjects in the Total column first, then the name
soc_order <- soc |>
filter(TRT == "Total") |>
select(AEBODSYS, soc_n = n)
pt_order <- pt |>
filter(TRT == "Total") |>
select(AEBODSYS, AEDECOD, pt_n = n)
layout <- bind_rows(mutate(any, AEBODSYS = "ANY TEAE"), soc, pt) |>
complete(TRT, nesting(AEBODSYS, AEDECOD), fill = list(n = 0)) |>
left_join(bign, by = "TRT") |>
mutate(value = n_pct(n, N)) |>
select(AEBODSYS, AEDECOD, TRT, value) |>
pivot_wider(names_from = TRT, values_from = value) |>
left_join(soc_order, by = "AEBODSYS") |>
left_join(pt_order, by = c("AEBODSYS", "AEDECOD")) |>
arrange(
AEBODSYS != "ANY TEAE", desc(soc_n), AEBODSYS,
!is.na(AEDECOD), desc(pt_n), AEDECOD
) |>
mutate(label = if_else(is.na(AEDECOD), AEBODSYS, paste0(" ", AEDECOD)))
saveRDS(layout, "output/t_ae.rds")
# the first 10 lines (labels cut at 40 characters for the screen)
nrow(layout)
#> [1] 254
options(width = 90)
layout |>
select(label, Placebo:Total) |>
mutate(label = stringr::str_trunc(label, 40)) |>
head(10) |>
as.data.frame() |>
print(right = FALSE, row.names = FALSE)
#> label Placebo Low Dose High Dose Total
#> ANY TEAE 65 (75.6%) 84 (87.5%) 68 (94.4%) 217 (85.4%)
#> GENERAL DISORDERS AND ADMINISTRATION ... 21 (24.4%) 51 (53.1%) 36 (50.0%) 108 (42.5%)
#> APPLICATION SITE PRURITUS 6 (7.0%) 23 (24.0%) 21 (29.2%) 50 (19.7%)
#> APPLICATION SITE ERYTHEMA 3 (3.5%) 13 (13.5%) 14 (19.4%) 30 (11.8%)
#> APPLICATION SITE DERMATITIS 5 (5.8%) 9 (9.4%) 7 (9.7%) 21 (8.3%)
#> APPLICATION SITE IRRITATION 3 (3.5%) 9 (9.4%) 9 (12.5%) 21 (8.3%)
#> APPLICATION SITE VESICLES 1 (1.2%) 5 (5.2%) 5 (6.9%) 11 (4.3%)
#> FATIGUE 1 (1.2%) 5 (5.2%) 5 (6.9%) 11 (4.3%)
#> OEDEMA PERIPHERAL 2 (2.3%) 1 (1.0%) 2 (2.8%) 5 (2.0%)
#> APPLICATION SITE SWELLING 0 (0.0%) 1 (1.0%) 2 (2.8%) 3 (1.2%)
# subject 01-701-1015: three events, two SOCs
teae |>
filter(USUBJID == "01-701-1015", TRT == "Placebo") |>
select(AEBODSYS, AEDECOD)
#> # A tibble: 3 x 2
#> AEBODSYS AEDECOD
#> <chr> <chr>
#> 1 GENERAL DISORDERS AND ADMINISTRATION SITE CONDITIONS APPLICATION SITE ERYTHEMA
#> 2 GENERAL DISORDERS AND ADMINISTRATION SITE CONDITIONS APPLICATION SITE PRURITUS
#> 3 GASTROINTESTINAL DISORDERS DIARRHOEA
  • with_total() is a small function that adds the Total column. ADSL (for the big N) and ADAE (for the counts) both need it, so it is written once (chapter 8).
  • Three levels, three counts. distinct() keeps one row per subject and level before count() counts. A subject with two headaches counts once in the HEADACHE line. A subject with a headache and dizziness counts once in the SOC line. Never add the PT lines to get the SOC line.
  • The grid again. complete() gives every line a cell in every column. The SOC rows have AEDECOD = NA; nesting() keeps them as they are.
  • The order. Many shells ask for the most frequent first. soc_order and pt_order take the number of subjects in the Total column. arrange() sorts by them: the first line, then the SOC by frequency, inside the SOC its own line first (!is.na(AEDECOD) is FALSE for it), then the PTs by frequency. The name breaks a tie, so the order is the same each time.
  • The label is the SOC, or the PT indented by two blanks.

The table has 254 lines. The first line is a number you know from chapter 1: 65 of the 86 subjects on placebo had at least one TEAE, 75.6%. The largest SOC is GENERAL DISORDERS AND ADMINISTRATION SITE CONDITIONS, with 108 subjects in total.

Exercise 13-2. How many subjects had at least one serious TEAE (AESER == "Y") in each column? Show the zero.

Exercise 13-3. Which three system organ classes have the most subjects, all treatments together?

Every company has a table library, and in R two packages are shared by the whole industry. The first, gtsummary, makes a summary table from a data frame with one function call.

programs/13_5_gtsummary.R
# Chapter 13: the demographics table with gtsummary
library(dplyr)
library(gtsummary)
cols <- c(
"Placebo" = "Placebo", "Low Dose" = "Xanomeline Low Dose",
"High Dose" = "Xanomeline High Dose"
)
adsl <- pharmaverseadam::adsl |>
filter(SAFFL == "Y") |>
mutate(TRT = factor(TRT01A, levels = cols, labels = names(cols)))
demog <- adsl |>
tbl_summary(
by = TRT,
include = c(AGE, AGEGR1, SEX, RACE),
type = AGE ~ "continuous2",
statistic = list(
AGE ~ c("{N_nonmiss}", "{mean} ({sd})", "{median}", "{min}, {max}"),
all_categorical() ~ "{n} ({p}%)"
),
digits = list(AGE ~ c(0, 1, 2, 1, 0, 0), all_categorical() ~ c(0, 1)),
label = list(
AGE ~ "Age (years)", AGEGR1 ~ "Age group", SEX ~ "Sex", RACE ~ "Race"
)
) |>
add_overall(last = TRUE, col_label = "**Total** \nN = {N}")
saveRDS(demog, "output/t_demog_gts.rds")
# the table as text: one row per printed line, one column per treatment
options(width = 90)
demog |>
as_tibble(col_labels = FALSE) |>
as.data.frame() |>
print(na.print = "", right = FALSE, row.names = FALSE)
#> label stat_1 stat_2 stat_3 stat_0
#> Age (years)
#> N Non-missing 86 96 72 254
#> Mean (SD) 75.2 (8.59) 76.0 (8.11) 73.8 (7.94) 75.1 (8.25)
#> Median 76.0 78.0 75.5 77.0
#> Min, Max 52, 89 51, 88 56, 88 51, 89
#> Age group
#> 18-64 14 (16.3%) 8 (8.3%) 11 (15.3%) 33 (13.0%)
#> >64 72 (83.7%) 88 (91.7%) 61 (84.7%) 221 (87.0%)
#> Sex
#> F 53 (61.6%) 55 (57.3%) 35 (48.6%) 143 (56.3%)
#> M 33 (38.4%) 41 (42.7%) 37 (51.4%) 111 (43.7%)
#> Race
#> AMERICAN INDIAN OR ALASKA NATIVE 0 (0.0%) 0 (0.0%) 1 (1.4%) 1 (0.4%)
#> BLACK OR AFRICAN AMERICAN 8 (9.3%) 6 (6.3%) 9 (12.5%) 23 (9.1%)
#> WHITE 78 (90.7%) 90 (93.8%) 62 (86.1%) 230 (90.6%)

tbl_summary() does jobs 2 and 3 in one call:

  • by = TRT makes the columns, and include names the variables. Each variable becomes a section.
  • type = AGE ~ "continuous2" gives age several lines, one per statistic. The default is one line.
  • statistic says what each line shows, as a text with the statistics in braces. "{n} ({p}%)" is the count and the percent.
  • digits gives the decimals of each statistic: for age, 0 for n, 1 for the mean, 2 for the SD, and so on.
  • add_overall() adds the Total column.

The ~ makes a formula: on the left the variables, on the right the value for them. all_categorical() selects every categorical variable.

A gtsummary table is made to be shown as HTML or Word (13.8). as_tibble() gives its cells as text, so you can read it in the console. Compare it with 13.2: the numbers are the same, line by line. The line N Non-missing is the n of the table by hand.

The adverse event table uses tbl_hierarchical():

programs/13_6_gtsummary_ae.R
# Chapter 13: the adverse event table with gtsummary::tbl_hierarchical()
library(dplyr)
library(gtsummary)
cols <- c(
"Placebo" = "Placebo", "Low Dose" = "Xanomeline Low Dose",
"High Dose" = "Xanomeline High Dose"
)
adsl <- pharmaverseadam::adsl |>
filter(SAFFL == "Y") |>
mutate(TRT = factor(TRT01A, levels = cols, labels = names(cols)))
teae <- pharmaverseadam::adae |>
filter(SAFFL == "Y", TRTEMFL == "Y") |>
mutate(TRT = factor(TRT01A, levels = cols, labels = names(cols)))
ae <- teae |>
tbl_hierarchical(
variables = c(AEBODSYS, AEDECOD),
by = TRT,
id = USUBJID, # count subjects, not records
denominator = adsl, # percent of the big N
overall_row = TRUE,
statistic = everything() ~ "{n} ({p}%)",
digits = everything() ~ list(n = 0, p = 1),
label = list(..ard_hierarchical_overall.. = "ANY TEAE")
) |>
add_overall(last = TRUE) |>
sort_hierarchical()
saveRDS(ae, "output/t_ae_gts.rds")
options(width = 90)
ae |>
as_tibble(col_labels = FALSE) |>
mutate(label = stringr::str_trunc(label, 40)) |>
head(10) |>
as.data.frame() |>
print(right = FALSE, row.names = FALSE)
#> label stat_1 stat_2 stat_3 stat_0
#> ANY TEAE 65 (75.6%) 84 (87.5%) 68 (94.4%) 217 (85.4%)
#> GENERAL DISORDERS AND ADMINISTRATION ... 21 (24.4%) 51 (53.1%) 36 (50.0%) 108 (42.5%)
#> APPLICATION SITE PRURITUS 6 (7.0%) 23 (24.0%) 21 (29.2%) 50 (19.7%)
#> APPLICATION SITE ERYTHEMA 3 (3.5%) 13 (13.5%) 14 (19.4%) 30 (11.8%)
#> APPLICATION SITE DERMATITIS 5 (5.8%) 9 (9.4%) 7 (9.7%) 21 (8.3%)
#> APPLICATION SITE IRRITATION 3 (3.5%) 9 (9.4%) 9 (12.5%) 21 (8.3%)
#> APPLICATION SITE VESICLES 1 (1.2%) 5 (5.2%) 5 (6.9%) 11 (4.3%)
#> FATIGUE 1 (1.2%) 5 (5.2%) 5 (6.9%) 11 (4.3%)
#> OEDEMA PERIPHERAL 2 (2.3%) 1 (1.0%) 2 (2.8%) 5 (2.0%)
#> APPLICATION SITE SWELLING 0 (0.0%) 1 (1.0%) 2 (2.8%) 3 (1.2%)
  • variables = c(AEBODSYS, AEDECOD) gives the levels: SOC, then PT inside the SOC.
  • id = USUBJID counts subjects, not records. Without it, the function counts events.
  • denominator = adsl takes the big N from ADSL. The percents divide by 86, 96 and 72.
  • overall_row = TRUE adds the first line, and label names it.
  • sort_hierarchical() sorts the SOCs and the PTs by frequency, the most frequent first.

The first 10 lines are those of 13.4.

Exercise 13-5. Make the TEAE table with tbl_hierarchical() for severe events only (AESEV == "SEVERE"). How many subjects in each column had at least one severe TEAE?

rtables works the other way round. You first describe the table in a layout, with no data. Then build_table() applies the layout to the data.

programs/13_7_rtables.R
# Chapter 13: the demographics table with rtables: a layout, then build_table()
library(dplyr)
library(rtables)
cols <- c(
"Placebo" = "Placebo", "Low Dose" = "Xanomeline Low Dose",
"High Dose" = "Xanomeline High Dose"
)
adsl <- pharmaverseadam::adsl |>
filter(SAFFL == "Y") |>
mutate(
TRT = factor(TRT01A, levels = cols, labels = names(cols)),
AGEGR1 = factor(AGEGR1, c("18-64", ">64")),
SEX = factor(SEX),
RACE = factor(RACE)
)
# an analysis function returns the cells of its lines: values and a format
a_age <- function(x) {
in_rows(
"n" = length(x), "Mean (SD)" = c(mean(x), sd(x)), "Median" = median(x),
"Min, Max" = range(x),
.formats = c("xx", "xx.x (xx.xx)", "xx.x", "xx, xx")
)
}
a_count <- function(x, .N_col) {
counts <- as.list(table(x))
in_rows(
.list = lapply(counts, function(n) c(n, n / .N_col)),
.formats = "xx (xx.x%)"
)
}
lyt <- basic_table(show_colcounts = TRUE, round_type = "sas") |>
split_cols_by("TRT") |>
add_overall_col("Total") |>
analyze("AGE", a_age, var_labels = "Age (years)", show_labels = "visible") |>
analyze(
c("AGEGR1", "SEX", "RACE"), a_count,
var_labels = c("Age group", "Sex", "Race"), show_labels = "visible"
)
demog <- build_table(lyt, adsl)
demog
#> Placebo Low Dose High Dose Total
#> (N=86) (N=96) (N=72) (N=254)
#> ——————————————————————————————————————————————————————————————————————————————————————————
#> Age (years)
#> n 86 96 72 254
#> Mean (SD) 75.2 (8.59) 76.0 (8.11) 73.8 (7.94) 75.1 (8.25)
#> Median 76.0 78.0 75.5 77.0
#> Min, Max 52, 89 51, 88 56, 88 51, 89
#> Age group
#> 18-64 14 (16.3%) 8 (8.3%) 11 (15.3%) 33 (13.0%)
#> >64 72 (83.7%) 88 (91.7%) 61 (84.7%) 221 (87.0%)
#> Sex
#> F 53 (61.6%) 55 (57.3%) 35 (48.6%) 143 (56.3%)
#> M 33 (38.4%) 41 (42.7%) 37 (51.4%) 111 (43.7%)
#> Race
#> AMERICAN INDIAN OR ALASKA NATIVE 0 (0.0%) 0 (0.0%) 1 (1.4%) 1 (0.4%)
#> BLACK OR AFRICAN AMERICAN 8 (9.3%) 6 (6.3%) 9 (12.5%) 23 (9.1%)
#> WHITE 78 (90.7%) 90 (93.8%) 62 (86.1%) 230 (90.6%)
saveRDS(demog, "output/t_demog_rtables.rds")
# the format rounds the percent: as R does by default, or as SAS does
formatters::format_value(c(6, 6 / 96), "xx (xx.x%)")
#> [1] "6 (6.2%)"
formatters::format_value(c(6, 6 / 96), "xx (xx.x%)", round_type = "sas")
#> [1] "6 (6.3%)"
  • basic_table(show_colcounts = TRUE) starts the layout and prints the big N under each column header.
  • split_cols_by("TRT") makes one column per treatment, and add_overall_col("Total") adds the Total.
  • analyze("AGE", a_age) adds the lines of one variable. a_age() is an analysis function: it gets the values of one column and returns the cells, with in_rows(). Each cell has values and a format: "xx.x (xx.xx)" prints the mean with one decimal and the SD with two.
  • a_count() has an argument with a special name, .N_col. rtables gives it the big N of the column, so n / .N_col is the fraction for the percent.

Three programs made the demographics table, and two made the AE table. Do they agree? Do not compare by eye. A program compares them cell by cell:

programs/13_8_compare.R
# Chapter 13: compare the tables by hand with gtsummary and rtables
library(dplyr)
library(tidyr)
library(gtsummary)
library(rtables)
# every table as cells: one row per line and column, with the printed text
cells <- function(table) {
table |>
select(label, Placebo, `Low Dose`, `High Dose`, Total) |>
mutate(label = trimws(label)) |>
pivot_longer(-label, names_to = "column", values_to = "text")
}
from_gts <- function(gts) {
as_tibble(gts, col_labels = FALSE) |>
filter(!is.na(stat_1)) |>
rename(
Placebo = stat_1, `Low Dose` = stat_2, `High Dose` = stat_3,
Total = stat_0
) |>
mutate(label = if_else(label == "N Non-missing", "n", label))
}
compare <- function(a, b) {
full_join(cells(a), cells(b), by = c("label", "column")) |>
summarise(cells = n(), same = sum(text.x == text.y, na.rm = TRUE))
}
hand <- readRDS("output/t_demog.rds") # 13_2
gts <- readRDS("output/t_demog_gts.rds") |> from_gts() # 13_5
rtb <- readRDS("output/t_demog_rtables.rds") |> # 13_7
as_result_df(data_format = "strings") |>
rename(label = label_name)
compare(hand, gts)
#> # A tibble: 1 x 2
#> cells same
#> <int> <int>
#> 1 44 44
compare(hand, rtb)
#> # A tibble: 1 x 2
#> cells same
#> <int> <int>
#> 1 44 44
# the adverse event table: the same cells, and the same order of lines?
hand_ae <- readRDS("output/t_ae.rds") # 13_4
gts_ae <- readRDS("output/t_ae_gts.rds") |> from_gts() # 13_6
compare(hand_ae, gts_ae)
#> # A tibble: 1 x 2
#> cells same
#> <int> <int>
#> 1 1016 1016
identical(trimws(hand_ae$label), gts_ae$label)
#> [1] TRUE
  • cells() turns any of the tables into one row per line and column, with the printed text.
  • from_gts() gives the gtsummary columns the names of the table by hand, and renames N Non-missing to n.
  • compare() joins two tables on the line and the column, and counts the cells with the same text.

All 44 cells of the demographics table agree with gtsummary, and all 44 agree with rtables. All 1016 cells of the AE table agree with gtsummary (254 lines, 4 columns), and the order of the lines is the same: identical() gives TRUE.

This is the method of double programming (chapter 15): two independent ways to the same table, and a program that compares them. Here, the first way is the one you can read line by line. When a package gives a number that you cannot explain, the table by hand shows where it comes from.

The statistician and the medical writer do not read the console. They get a file.

programs/13_9_write.R
# Chapter 13: deliver the demographics table as HTML (gt) and Word (flextable)
library(dplyr)
library(gtsummary)
library(flextable)
library(officer)
# HTML: the gtsummary table of 13_5, through gt
readRDS("output/t_demog_gts.rds") |>
as_gt() |>
gt::tab_header(title = "Table 14.1.1 Demographics (safety population)") |>
gt::gtsave("output/t_14_1_1_demog.html")
# Word: the table by hand of 13_2, with the big N in the column headers
layout <- readRDS("output/t_demog.rds")
arms <- c(
"Placebo" = "Placebo", "Low Dose" = "Xanomeline Low Dose",
"High Dose" = "Xanomeline High Dose", "Total" = "Total"
)
saf <- pharmaverseadam::adsl |> filter(SAFFL == "Y")
bign <- c(table(saf$TRT01A)[arms[1:3]], Total = nrow(saf))
headers <- setNames(paste0(arms, "\n(N=", bign, ")"), names(arms))
headers <- c(label = "", headers)
headers
#> label Placebo
#> "" "Placebo\n(N=86)"
#> Low Dose High Dose
#> "Xanomeline Low Dose\n(N=96)" "Xanomeline High Dose\n(N=72)"
#> Total
#> "Total\n(N=254)"
ft <- layout |>
as_grouped_data(groups = "section") |>
as_flextable(hide_grouplabel = TRUE) |>
set_header_labels(values = as.list(headers)) |>
align(j = 2:5, align = "center", part = "all") |>
bold(i = ~ !is.na(section), part = "body") |>
autofit()
read_docx() |>
body_add_par("Table 14.1.1 Demographics (safety population)",
style = "heading 2"
) |>
body_add_flextable(ft) |>
print(target = "output/t_14_1_1_demog.docx")
file.exists(c("output/t_14_1_1_demog.html", "output/t_14_1_1_demog.docx"))
#> [1] TRUE TRUE
# read the Word file back: the header, then two lines of the table
word <- read_docx("output/t_14_1_1_demog.docx") |>
docx_summary() |>
filter(content_type == "table cell")
word |>
filter(row_id == 1) |>
pull(text)
#> [1] "" "Placebo\n(N=86)"
#> [3] "Xanomeline Low Dose\n(N=96)" "Xanomeline High Dose\n(N=72)"
#> [5] "Total\n(N=254)"
word |>
filter(row_id %in% 3:4) |>
select(row_id, cell_id, text) |>
tidyr::pivot_wider(names_from = cell_id, values_from = text)
#> # A tibble: 2 x 6
#> row_id `1` `2` `3` `4` `5`
#> <int> <chr> <chr> <chr> <chr> <chr>
#> 1 3 n 86 96 72 254
#> 2 4 Mean (SD) 75.2 (8.59) 76.0 (8.11) 73.8 (7.94) 75.1 (8.25)
  • HTML with gt. as_gt() turns the gtsummary table into a gt table, tab_header() adds the title, and gtsave() writes the HTML page.
  • Word with flextable and officer. flextable makes a table for Word and PowerPoint. as_grouped_data() makes a heading line for each section, set_header_labels() puts the big N into the column headers (\n starts a new line), and bold() makes the heading lines bold. officer makes the Word file: read_docx() starts an empty document, body_add_par() adds the title and body_add_flextable() the table. print(target = ...) writes the file.
  • Read it back. docx_summary() reads the Word file as a data frame, one row per paragraph or table cell. The header has Placebo\n(N=86), and the line n has 86, 96, 72 and 254. Check the file you send, not only the data that made it.

The two files are in programs/output/. Open them: the HTML file in a browser, the Word file in Word.

Which way for which job:

Job By hand (dplyr, tidyr) gtsummary rtables
Learn and check where a number comes from yes
A standard demographics or AE table, fast tbl_summary(), tbl_hierarchical() analyze() with an analysis function
A layout that a package cannot make yes custom analysis functions
A file to deliver flextable (Word), gt (HTML) as_flex_table(), as_gt() export_as_txt(), export_as_pdf()
  • A table program does four jobs: population and big N, compute, arrange, print. Keep them apart.
  • The big N comes from ADSL with the population flag, by the actual treatment for a safety table. A Total column is the data stacked on itself.
  • Count subjects with distinct() before count(). complete() writes the zeros.
  • Round half up with your own function: round() and sprintf() round 6.25 to 6.2.
  • gtsummary (tbl_summary(), tbl_hierarchical()) and rtables (layout, then build_table()) make the same tables. Set round_type = "sas" in rtables.
  • Compare the tables cell by cell with a program, not by eye.
  • gt writes HTML, flextable and officer write Word. Read the file back to check it.

Exercises 13-1 to 13-5 are in the sections above:

  1. Exercise 13-1 (13.2): the ethnicity section.
  2. Exercise 13-2 (13.4): subjects with a serious TEAE, with the zero.
  3. Exercise 13-3 (13.4): the three largest system organ classes.
  4. Exercise 13-4 (13.3): the percents where the two rounding rules differ.
  5. Exercise 13-5 (13.5): the severe TEAE table with tbl_hierarchical().

The answers are in Answers, Part III.

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.