Generating tables, figures and listings in R
Decoupling clinical calculation from presentation across direct layout engines and Analysis Results Data
The problem
Tables, Figures, and Listings (TFLs) represent the bulk of clinical study deliverables. A Phase III Clinical Study Report (CSR) needs a long list of them: demographic baselines, adverse events grouped by system organ class, laboratory shifts, and patient listings.
Historically, statistical programming teams built TFLs through monolithic procedural scripts. A single program loaded data, filtered records, calculated summaries, formatted numbers like "75.2 (8.6)", injected Rich Text Format (RTF) control tags, and managed page breaks.
This coupling creates three chronic engineering problems:
- Re-deriving numbers per table: When Table 14.1.1 (demographics) and Table 14.3.1 (adverse events) independently recalculate population counts (N), subtle discrepancies in filtering or rounding rules emerge. Programmers and statisticians then spend time reconciling numbers across tables.
- Fragile layout and pagination: When a reviewer requests a cosmetic adjustment—such as altering decimal precision or moving footnotes—programmers must edit and re-run the entire script, forcing re-verification of the underlying statistical calculations.
- Opaque quality control: Double-programming verification often degenerates into visual inspection of rendered RTF or PDF documents. Reviewers end up scrutinising typographic margins instead of programmatically verifying numbers as data.
The web-repo way
Web engineering encountered this exact failure decades ago. In early web frameworks, SQL queries were embedded directly inside HTML markup. Altering a layout broke queries; changing a table schema crashed the user interface.
Modern web architectures solved this by separating data from presentation:
Database Layer ──> [API / Schema] ──> Structured Data ──> [Design System] ──> Presentation
(ADaM Data) (Stats Engine) (Typed JSON / ARD) (UI Components) (HTML / RTF)
- The data contract: The backend API serves structured, typed data (usually JSON) containing raw numbers and category labels, independent of fonts, margins, or page breaks.
- The presentation components: Client frameworks consume that structured payload and render it through reusable templates and visual components.
- The design system: Centralised design tokens dictate spacing, typography, and borders across every screen, ensuring visual consistency without redesigning tables on every page.
Applying this separation of concerns to clinical reporting replaces fragile monolithic scripts with two decoupled layers: an analytics engine that derives auditable numerical results, and a presentation engine that arranges those results into submission-ready displays.
The R way: two reporting architectures
The modern pharmaverse ecosystem provides two distinct architectural approaches for building clinical tables. Neither is universally superior; each addresses specific operational needs.
Architecture 1: Direct table code
Direct table generation builds formatted displays directly from ADaM data in a single declarative pipeline. This approach fits teams delivering standard clinical study reports with predefined table shells. Three primary packages lead this space:
1. {rtables} + {tern}
{rtables} models tables as hierarchical tree structures (basic_table(), split_cols_by(), analyze(), build_table()). You declare the layout first—specifying column splits and nested row hierarchies—before populating it with data. {tern} provides clinical analysis functions (such as analyze_vars()) built on {rtables}:
library(rtables)
library(tern)
adsl_saf <- subset(pharmaverseadam::adsl, SAFFL == "Y")
tbl_rtables <- basic_table(
title = "Demographic and Baseline Characteristics",
subtitles = "Safety Population",
main_footer = "Source: pharmaverseadam::adsl"
) |>
split_cols_by("TRT01A") |>
analyze_vars(
vars = c("AGE", "SEX"),
var_labels = c(AGE = "Age (Years)", SEX = "Sex")
) |>
build_table(adsl_saf){rtables} excels at complex, multi-level clinical tables—such as adverse events nested by System Organ Class and Preferred Term, or multi-arm summaries with nested column splits—while preserving cell-level metadata.
2. {Tplyr}
{Tplyr} provides an explicit “grammar of clinical tables”. It organizes table construction into modular analytical layers: count layers (group_count()), descriptive summary layers (group_desc()), and shift layers:
library(Tplyr)
adsl_saf <- subset(pharmaverseadam::adsl, SAFFL == "Y")
tbl_tplyr <- tplyr_table(adsl_saf, TRT01A) |>
add_layer(
group_desc(target_var = AGE, by = "Age (Years)")
) |>
add_layer(
group_count(target_var = SEX, by = "Sex")
) |>
build(){Tplyr} compiles these layers into an intermediate data frame with structured row labels and formatted character values, ready for any downstream formatting engine.
3. {gtsummary}
Built on top of {gt}, {gtsummary} offers a concise syntax for summary tables via tbl_summary():
library(gtsummary)
adsl_saf <- subset(pharmaverseadam::adsl, SAFFL == "Y")
tbl_gt <- adsl_saf |>
dplyr::select(TRT01A, AGE, SEX) |>
tbl_summary(
by = TRT01A,
label = list(AGE ~ "Age (Years)", SEX ~ "Sex"),
statistic = list(
AGE ~ "{mean} ({sd})",
SEX ~ "{n} ({p}%)"
)
){gtsummary} is widely used across clinical research and exploratory biostatistics, providing rapid prototyping and clean default styling.
Architecture 2: ARD-first (Analysis Results Data)
The second architecture separates statistical calculations entirely from table presentation by creating an intermediate dataset called Analysis Results Data (ARD).
In an ARD-first workflow, you never compute statistics inside a layout routine. Instead, an analytics engine derives a tidy, standardised results table containing calculated values, parameter names, grouping variables, and statistical context.
{cards} is the foundational pharmaverse package for generating ARDs. Functions like ard_continuous() and ard_categorical() calculate statistical summaries, while ard_stack() binds them into a consistent structure:
library(cards)
adsl_saf <- subset(pharmaverseadam::adsl, SAFFL == "Y")
ard <- ard_stack(
data = adsl_saf,
ard_continuous(variables = AGE),
ard_categorical(variables = SEX),
.by = TRT01A,
.attributes = TRUE
)The resulting ard object contains purely numerical results and metadata—no formatted strings, borders, or display logic. Presentation frameworks render it without re-running computations:
gtsummary::tbl_ard_summary(): Formats the pre-computed ARD into a presentation-ready display:
library(gtsummary)
tbl_rendered <- tbl_ard_summary(
cards = ard,
by = TRT01A,
label = list(AGE ~ "Age (Years)", SEX ~ "Sex"),
statistic = list(
AGE ~ "{mean} ({sd})",
SEX ~ "{n} ({p}%)"
)
){tfrmt}: The{tfrmt}(table format) package defines an external formatting language (tfrmt(),print_to_gt()) that applies visual layouts, decimal formatting, and row-grouping plans to pre-aggregated data.
Why ARD-first helps QC and re-use
Separating results into structured data delivers two substantial engineering advantages:
- QC as automated data comparison: In traditional double-programming, quality control requires comparing formatted text strings or visual reports. With ARD-first workflows, the primary and validation programmers each produce an ARD data frame. Independent verification becomes a structured data comparison (for example
waldo::compare()ordiffdf::diffdf()). Any discrepancy immediately highlights the exact variable, treatment arm, and statistic where the calculation diverged, without noise from whitespace or font differences. - One calculation, multiple presentations: A single ARD generated during an analysis run can render multiple downstream deliverables: a formal CSR submission table in RTF, an executive slide deck, an interactive safety dashboard in Shiny, or a web report. The underlying statistical numbers are computed and verified once.
Choosing between the two architectures
- Direct table code (
{rtables}or{Tplyr}) fits individual clinical studies with standard table shells and tight submission timelines, where producing a fixed set of CSR tables within a single framework is the primary objective. - ARD-first (
{cards}paired withtbl_ard_summary()or{tfrmt}) fits larger drug programmes, cross-study integrated summaries of safety (ISS), interactive reporting platforms, and teams transitioning toward standardized statistical data exchange.
Output formats and clinical publishing
Clinical trial reporting requires strict adherence to regulatory formatting guidelines:
- RTF via
{r2rtf}: RTF is still a common delivery format for CSR tables and listings.{r2rtf}provides granular programmatic control over submission RTFs (rtf_body(),rtf_encode(),write_rtf()), enabling precise configuration of margins, cell heights, borders, and page orientations. - RTF export via
{gt}:{gtsummary}tables (viaas_gt()) and{tfrmt}tables (viaprint_to_gt()) are{gt}objects, andgt::gtsave(gt_tbl, "table.rtf")writes them to RTF. - Patient listings via
{rlistings}: Patient listings demand specialised pagination and layout behaviour.{rlistings}(as_listing()) automatically suppresses repeating keys across successive rows (key_cols), and handles column wrapping and pagination for long listings:
library(rlistings)
adsl_saf <- subset(pharmaverseadam::adsl, SAFFL == "Y")
lsting <- as_listing(
df = adsl_saf,
key_cols = c("TRT01A", "USUBJID"),
disp_cols = c("TRT01A", "USUBJID", "AGE", "SEX", "RACE")
)- Clinical figures with
{ggplot2}: Figures must maintain consistent visual hierarchy across a CSR. Standardise a project-level theme (extendingtheme_minimal()ortheme_classic()) to enforce uniform font sizes, axis line widths, and colour palettes. - Titles, footnotes, and pagination conventions: In regulatory reporting, titles and footnotes represent auditable provenance metadata. Define study-wide conventions to capture the table identifier, analysis population, data cut-off date, and source script path on every page.
Team conventions and GxP discipline
Tool diversity without governance leads to fragmented pipelines. Applying software engineering discipline to TFL generation requires four shared team practices:
- One table framework per study or team: Standardising on
{rtables}or{Tplyr}across a team enables shared helper functions, uniform review standards, and collective code ownership. - The mock shell as a contract: Treat mock shells from the Statistical Analysis Plan as formal schema contracts. Specifying exact row labels, column splits, and statistic requirements upfront prevents miscommunication.
- Pinned runtime environments: Reproducible reporting requires pinning package versions using
renv. Discrepancies in package versions or operating system defaults can subtly alter text wrapping, pagination, or rounding behaviour across developer environments and CI runners. - Validation-ready mindset: An open-source R package cannot simply be declared “validated” off the shelf. Qualification is an organisational, risk-based assessment that evaluates whether a package is fit for its intended purpose within a qualified execution environment. Combine pinned dependencies with independent double-programming quality control to produce defensible, auditable clinical deliverables.
Pitfalls
- Different defaults for the same statistic: packages format numbers differently out of the box. In this post’s companion script (scripts/tfl-demo.R),
{gtsummary}’s default shows a median of 75.5 as “76”, while{rtables}+{tern}shows “75.5”. Put decimal places and rounding rules in the shell, and set them explicitly in code. - Formatting numbers inside ADaM datasets: Concatenating numbers into strings (such as
"75.2 (8.6)") within ADaM columns destroys their utility for subsequent analyses or modeling. Keep ADaM strictly numeric and typed; leave formatting strings to the presentation layer. - Fragile column width definitions: Hardcoding absolute column widths in characters or pixels often leads to clipped text or awkward wrapping when converting between HTML previews and landscape RTFs. Use proportional column widths wherever possible.
- Divergent Big-N denominators: Calculating percentage denominators from the filtered table subset rather than the true population total generates inaccurate percentages for sparse safety events. Ensure your table framework explicitly references the true population header counts.
- Mixing frameworks across study tables: Using
{rtables}for demographic tables and{Tplyr}for adverse events within the same study creates duplicated formatting utilities, complicates code reviews, and doubles the team’s package qualification surface.
Later posts explore generating Analysis Results Data with {cards} in depth, adopting the CDISC Analysis Results Standard (ARS), and establishing independent double-programming quality control in R.
Companion code
Builds a demographics summary table three ways: using {rtables} with {tern}, {gtsummary}, and an ARD dataset from {cards} rendered with {gtsummary}, exporting output via {gt}. Requires {pharmaverseadam}, {dplyr}, {rtables}, {tern}, {gtsummary}, {cards}, and {gt}.
tfl-demo.R
# One demographics summary, three ways: {rtables} + {tern}, {gtsummary}, and
# an Analysis Results Data (ARD) set from {cards} rendered with
# gtsummary::tbl_ard_summary(). Then writes the gtsummary table to RTF.
# Data: {pharmaverseadam} ADSL (example data, not real patients).
#
# Rscript tfl-demo.R
# Safety population, with factors so every table shows the same levels.
safety_adsl <- function(adsl = pharmaverseadam::adsl) {
adsl |>
dplyr::filter(SAFFL == "Y") |>
dplyr::mutate(TRT01A = factor(TRT01A), SEX = factor(SEX))
}
# 1. Direct table code: an rtables layout with a tern analysis function.
demog_rtables <- function(adsl) {
rtables::basic_table(
title = "Demographics",
subtitles = "Safety population"
) |>
rtables::split_cols_by("TRT01A") |>
rtables::add_overall_col("All patients") |>
tern::analyze_vars(
c("AGE", "SEX"),
var_labels = c(AGE = "Age (years)", SEX = "Sex")
) |>
rtables::build_table(adsl)
}
# 2. Direct table code: gtsummary.
demog_gtsummary <- function(adsl) {
gtsummary::tbl_summary(
adsl,
by = TRT01A,
include = c(AGE, SEX),
label = list(AGE = "Age (years)", SEX = "Sex")
)
}
# 3. ARD-first: compute the numbers as data, then render them.
demog_ard <- function(adsl) {
cards::ard_stack(
adsl,
.by = TRT01A,
cards::ard_continuous(variables = AGE),
cards::ard_categorical(variables = SEX),
.attributes = TRUE # variable labels, for the rendered table
)
}
demog_from_ard <- function(ard) {
gtsummary::tbl_ard_summary(
ard,
by = TRT01A,
label = list(AGE = "Age (years)", SEX = "Sex")
)
}
# RTF output via gt.
write_rtf <- function(tbl, path) {
gt::gtsave(gtsummary::as_gt(tbl), path)
invisible(path)
}
# Run only when called as a script (not when sourced by the tests).
if (sys.nframe() == 0L) {
adsl <- safety_adsl()
print(demog_rtables(adsl))
print(gtsummary::as_kable(demog_gtsummary(adsl)))
ard <- demog_ard(adsl)
print(ard[ard$stat_name == "mean", c("group1_level", "variable", "stat")])
print(gtsummary::as_kable(demog_from_ard(ard)))
path <- write_rtf(demog_gtsummary(adsl), file.path(tempdir(), "demog.rtf"))
message("RTF written to ", path)
}Sources
Standards and organisations
- pharmaverse initiative: pharmaverse.org
Package documentation
- pharmaverseadam: pharmaverse.github.io/pharmaverseadam
- rtables: CRAN
- tern: CRAN
- Tplyr: atorus-research.github.io/Tplyr
- gtsummary: danieldsjoberg.com/gtsummary
- cards: pharmaverse.github.io/cards
- tfrmt: CRAN
- r2rtf: CRAN
- gt: gt.rstudio.com
- rlistings: CRAN
- ggplot2: ggplot2.tidyverse.org
- waldo: waldo.r-lib.org
- diffdf: CRAN
- 2026-09-26: Removed the end-of-post checklist.
- 2026-09-27: Added a Sources section.
- 2026-09-27: Added a Companion code section with the full script.