The clinical reporting pipeline in R
From raw trial data to submission tables through modular, schema-driven stages
The problem
Clinical reporting transforms raw participant data from clinical trials into regulatory deliverables for health authorities like the US FDA, EMA, or PMDA. In legacy setups, this work often evolved as monolithic scripts. A single program would ingest raw files, impute dates, derive endpoints, and output tables in one opaque pass. When an audit query or discrepancy arose, locating where a value transformed meant untangling deeply nested procedural code.
Clinical reporting is not an undifferentiated script; it is a pipeline of distinct, standardised stages defined by CDISC (Clinical Data Interchange Standards Consortium). Each transition has an explicit purpose, specific input expectations, and strict regulatory standards.
When engineering an R-based clinical reporting stack, teams need to know exactly which package handles which stage. Without clear boundaries, developers reinvent ad-hoc derivations, mix data manipulation with visual layout, and defer metadata checks until right before submission deadlines.
The web-repo way
In data engineering and web platforms, production pipelines rely on strict schema contracts between decoupled stages:
Raw Ingestion ──> [Schema Contract] ──> Transformation Layer ──> [API Contract] ──> Presentation
(Webhooks) (JSON Schema / Protobuf) (dbt Models) (OpenAPI / GraphQL) (Client UI)
At every boundary, data does not advance unless it satisfies the contract:
- Ingestion endpoints reject payloads violating an explicit JSON Schema or Protocol Buffer definition.
- Transformation jobs (such as dbt models) operate on typed relations, running automated schema tests on every build.
- The presentation layer renders components against typed API responses without guessing whether a field contains an integer, a formatted string, or an unexpected null.
Applying this contract-first architecture to clinical programming turns an unpredictable script into an engineered pipeline. Rather than passing loosely structured data frames between ad-hoc scripts, each stage transforms data to satisfy an explicit specification before handing it downstream.
The R way, stage by stage
The modern R clinical ecosystem, organised primarily under the pharmaverse initiative, provides specialised packages aligned to each CDISC stage.
Understanding the CDISC terminology
Before examining the packages, here is how the core CDISC artifacts connect:
- CRF / Raw data: Case Report Forms recorded in electronic data capture (EDC) systems. These contain operational tracking fields, site-specific formats, and unstandardised coding.
- SDTM (Study Data Tabulation Model): Standardises raw data across trials into consistent domains (
DMfor demographics,AEfor adverse events,VSfor vital signs) with standardised variable names, types, and controlled terminology. - ADaM (Analysis Data Model): Analysis-ready datasets derived from SDTM. ADaM datasets add derived timing windows, baseline flags, treatment allocations, and endpoint calculations (
ADSLfor subject-level analysis,ADAEfor adverse events,ADTTEfor time-to-event). - TLFs / TFLs (Tables, Listings, and Figures): The statistical summaries, individual patient listings, and graphical displays that populate the Clinical Study Report (CSR).
- define.xml: The machine-readable XML specification that describes the structure, variable definitions, controlled terminologies, derivation algorithms, and origins of all submitted datasets.
- XPT and Dataset-JSON: The data exchange formats used for regulatory submissions. SAS Transport Version 5 (XPT v5) has long been the primary submission format required by regulators. CDISC Dataset-JSON is a modern, lightweight JSON standard designed to exchange clinical datasets without XPT v5 limitations, such as 8-character variable names or 200-character string constraints.
The R package ecosystem by stage
| Pipeline Stage | What it produces | R Packages |
|---|---|---|
| Raw → SDTM | Standardised SDTM domains (DM, AE, VS) |
{sdtm.oak} |
| Metadata Specification | Machine-readable specification objects | {metacore}, {metatools} |
| SDTM → ADaM | Analysis-ready datasets (ADSL, ADAE, ADTTE) |
{admiral} (+ extensions) |
| Example & Test Data | Reusable SDTM and ADaM datasets for tests | {pharmaversesdtm}, {pharmaverseadam} |
| Submission Export | XPT v5 or Dataset-JSON files, checked against the specification | {xportr}, {datasetjson} |
| TFL Generation | Paginated tables, listings, and RTF/HTML outputs | {rtables} + {tern}, {gtsummary}, {Tplyr}, {tfrmt}, {rlistings}, {r2rtf} |
| Analysis Results Data | Tidy statistical results tables (ARD) | {cards}, {cardx} |
Raw → SDTM: {sdtm.oak}
Mapping raw EDC tables to SDTM domains involves recurring transformation patterns: creating ISO-8601 dates, mapping terms to CDISC controlled terminology, and handling condition-based assignments. Rather than bespoke scripts, {sdtm.oak} provides reusable mapping algorithms, such as assign_datetime(), hardcode_ct() and create_iso8601(), to build reproducible SDTM mapping code.
Metadata-driven work: {metacore} and {metatools}
In legacy pipelines, specifications were often buried inside spreadsheets that programmers manually referenced. {metacore} imports trial specifications directly from spreadsheets or define.xml files (spec_to_metacore(), define_to_metacore()), holding dataset definitions, variable types, lengths and controlled terminology codelists in one immutable R object.
{metatools} pairs with {metacore} to apply and verify metadata at runtime. Functions like check_variables() verify that a dataset matches its specification, check_ct_col() confirms that values adhere to controlled terminology, and set_variable_labels() assigns attributes directly from the spec.
ADaM: {admiral}
Deriving ADaM datasets requires applying specific clinical rules: imputing partial dates, determining baseline values, and calculating study days. Instead of monolithic macros, {admiral} provides composable, modular derive_* functions designed to work directly with tidyverse workflows.
Beyond the core package, verified therapeutic area extensions on pharmaverse.org include: - {admiralonco} for Oncology endpoints - {admiralophtha} for Ophthalmology assessments - {admiralvaccine} for Vaccine trials - {admiralpeds} for Paediatric studies - {admiralmetabolic} for Metabolic trials - {admiralneuro} for Neuroscience assessments
Here is the shape of an {admiral} derivation: the first dose date for each subject, merged from exposure (EX) onto demographics (DM). It’s an excerpt from this post’s script (below), which runs.
library(admiral)
# Exposure records with a start datetime; a dose > 0, or placebo, counts.
ex_ext <- pharmaversesdtm::ex |>
derive_vars_dtm(dtc = EXSTDTC, new_vars_prefix = "EXST") |>
dplyr::filter(
(EXDOSE > 0 | (EXDOSE == 0 & grepl("PLACEBO", EXTRT))) & !is.na(EXSTDTM)
)
adsl <- pharmaversesdtm::dm |>
dplyr::mutate(TRT01P = ARM, TRT01A = ACTARM) |>
derive_vars_merged(
dataset_add = ex_ext,
by_vars = exprs(STUDYID, USUBJID),
order = exprs(EXSTDTM, EXSEQ),
new_vars = exprs(TRTSDTM = EXSTDTM),
mode = "first"
) |>
derive_vars_dtm_to_dt(source_vars = exprs(TRTSDTM))Each derive_*() call takes a dataset and returns it with new variables, so a derivation reads top to bottom, and each step can be tested on its own.
Example data: {pharmaversesdtm} and {pharmaverseadam}
Reliable unit tests and reproducible examples require standardised test data. {pharmaversesdtm} provides SDTM datasets (dm, ae, lb, vs, …) from the CDISC pilot project. {pharmaverseadam} provides ADaM datasets built from them with {admiral} and its extensions (adsl, adae, adlb, adtte_onco, …). These packages allow teams to test derivation logic and develop reporting templates before live trial data arrives.
The post script scripts/pipeline-demo.R takes SDTM DM and EX from {pharmaversesdtm}, derives a small ADSL with {admiral} (treatment dates, a safety population flag, age groups), and prints a demographics table by treatment arm with {rtables}. It has tests, like every script on this site.
Regulatory export: {xportr} and {datasetjson}
Creating an ADaM dataset is not the final step; regulatory agencies enforce strict file requirements. {xportr} reads your {metacore} specification and systematically applies variable types (xportr_type()), variable lengths (xportr_length()), labels (xportr_label()), formats (xportr_format()), and sorting orders (xportr_order()), before writing the XPT v5 file with xportr_write().
For modern submissions, {datasetjson} provides utilities to write (write_dataset_json()), read (read_dataset_json()), and validate (validate_dataset_json()) CDISC Dataset-JSON files.
Tables, Listings, and Figures (TFLs)
When presenting study results, the R ecosystem offers distinct packages tailored to different reporting architectures:
{rtables}+{tern}:{rtables}provides a hierarchical layout engine for multi-level clinical tables, while{tern}supplies clinical analysis functions built on top of it.{gtsummary}: Summary and regression tables (for exampletbl_summary()), widely used outside pharma too.{Tplyr}: Features an explicit grammar of clinical table construction, separating data extraction, summarisation (counts, shifts, descriptive statistics), and formatting.{tfrmt}: Provides a decoupled table formatting language that applies visual styling, alignment, and display rules to pre-aggregated data.{rlistings}: Builds formatted, paginated patient listings with key column grouping designed for Clinical Study Report appendices.{r2rtf}: Writes tables and listings to paginated Rich Text Format (RTF) documents, with control over margins and fonts.
Analysis Results Data: {cards} and {cardx}
Traditional workflows compute summary statistics directly inside table-formatting routines, tightly coupling calculation with presentation. Analysis Results Data (ARD) decouples these responsibilities: {cards} and {cardx} calculate statistical summaries and store them in tidy, standardised tabular structures. The same idea underlies the CDISC Analysis Results Standard (ARS): results stored as data can be checked and re-rendered without being recomputed. Later posts cover both.
Package qualification in GxP environments
In regulated clinical reporting, an open-source R package cannot simply be declared “validated” off the shelf. Validation is an organisational, risk-based process applied to an intended use within a qualified environment. The R Validation Hub provides a risk-based framework for evaluating package quality, and {riskmetric} collects metrics about a package, such as test coverage, documentation and maintenance activity, to inform that assessment. Later posts in this series will explore qualification pipelines, risk assessments, and double-programming quality control in detail.
Pitfalls
- Treating example datasets as production inputs: Packages like
{pharmaversesdtm}and{pharmaverseadam}are designed for prototyping, unit testing, and onboarding. Production pipelines must ingest verified study datasets that have completed formal clinical data-management reconciliation. - Mixing specification versions mid-pipeline: If your ADaM derivation code assumes one version of a variable definition while
{metacore}or the targetdefine.xmlreferences another, discrepancies emerge during export. Pin your specification objects and track them under version control. - Deferring metadata checks until final export: Running
{xportr}or{metatools}checks only at filing time turns missing labels, truncated lengths, and invalid codelist values into emergency firefighting. Run specification checks on every build in CI. - Selecting TFL packages per programmer: Allowing each programmer on a study to select their preferred table package (
{rtables}on one domain,{Tplyr}on another,{gtsummary}on a third) fragments code review, duplicates helper code, and complicates quality control. Standardise on a unified reporting framework across the project or team.
Later posts in this series explore TFL generation in depth, generating Analysis Results Data with {cards}, working with the CDISC Analysis Results Standard (ARS), and establishing qualification pipelines and quality control for validation-ready R packages.
Companion code
View pipeline-demo.R · Download
Takes SDTM DM and EX datasets from {pharmaversesdtm}, derives an ADSL data frame with {admiral}, and creates a summary demographics table by treatment arm using {rtables}. Requires {admiral}, {pharmaversesdtm}, {dplyr}, and {rtables}.
pipeline-demo.R
# SDTM -> ADaM -> TFL in one small script. Takes SDTM DM and EX from
# {pharmaversesdtm} (example data, not real patients), derives a small ADSL
# with {admiral}, and prints a demographics table by treatment arm with
# {rtables}.
#
# Rscript pipeline-demo.R
library(admiral)
# ADaM: one row per subject, with treatment variables, the first and last
# dose dates from EX, a safety population flag and an age group.
derive_adsl <- function(dm = pharmaversesdtm::dm, ex = pharmaversesdtm::ex) {
# Exposure records with a start datetime; a dose > 0, or a placebo record,
# counts as treated.
ex_ext <- ex |>
derive_vars_dtm(dtc = EXSTDTC, new_vars_prefix = "EXST") |>
dplyr::filter(
(EXDOSE > 0 | (EXDOSE == 0 & grepl("PLACEBO", EXTRT))) &
!is.na(EXSTDTM)
)
dm |>
dplyr::mutate(TRT01P = ARM, TRT01A = ACTARM) |>
derive_vars_merged(
dataset_add = ex_ext,
by_vars = exprs(STUDYID, USUBJID),
order = exprs(EXSTDTM, EXSEQ),
new_vars = exprs(TRTSDTM = EXSTDTM),
mode = "first"
) |>
derive_vars_merged(
dataset_add = ex_ext,
by_vars = exprs(STUDYID, USUBJID),
order = exprs(EXSTDTM, EXSEQ),
new_vars = exprs(TRTEDTM = EXSTDTM),
mode = "last"
) |>
derive_vars_dtm_to_dt(source_vars = exprs(TRTSDTM, TRTEDTM)) |>
derive_var_merged_exist_flag(
dataset_add = ex,
by_vars = exprs(STUDYID, USUBJID),
new_var = SAFFL,
condition = (EXDOSE > 0 | (EXDOSE == 0 & grepl("PLACEBO", EXTRT))),
false_value = "N",
missing_value = "N" # no EX records at all (e.g. screen failures)
) |>
dplyr::mutate(
AGEGR1 = factor(
dplyr::case_when(
AGE < 65 ~ "<65",
AGE <= 80 ~ "65-80",
AGE > 80 ~ ">80"
),
levels = c("<65", "65-80", ">80")
)
)
}
# TFL: demographics of the safety population, by actual treatment.
demographics_table <- function(adsl) {
saf <- adsl |>
dplyr::filter(SAFFL == "Y") |>
dplyr::mutate(TRT01A = factor(TRT01A), SEX = factor(SEX))
rtables::basic_table(
title = "Demographics",
subtitles = "Safety population (example data)"
) |>
rtables::split_cols_by("TRT01A") |>
rtables::add_overall_col("All patients") |>
rtables::analyze(
c("AGE", "AGEGR1", "SEX"),
var_labels = c("Age (years)", "Age group", "Sex")
) |>
rtables::build_table(saf)
}
# Run only when called as a script (not when sourced by the tests).
if (sys.nframe() == 0L) {
adsl <- derive_adsl()
message(
nrow(adsl),
" subjects in ADSL; ",
sum(adsl$SAFFL == "Y"),
" in the safety population"
)
print(demographics_table(adsl))
}Sources
Standards and organisations
- pharmaverse initiative: pharmaverse.org
- R Validation Hub: pharmar.org
Package documentation
- sdtm.oak: pharmaverse.github.io/sdtm.oak
- metacore: atorus-research.github.io/metacore
- metatools: pharmaverse.github.io/metatools
- admiral: pharmaverse.github.io/admiral
- pharmaversesdtm: pharmaverse.github.io/pharmaversesdtm
- pharmaverseadam: pharmaverse.github.io/pharmaverseadam
- xportr: atorus-research.github.io/xportr
- datasetjson: atorus-research.github.io/datasetjson
- rtables: CRAN
- tern: CRAN
- gtsummary: danieldsjoberg.com/gtsummary
- Tplyr: atorus-research.github.io/Tplyr
- tfrmt: CRAN
- rlistings: CRAN
- r2rtf: CRAN
- cards: pharmaverse.github.io/cards
- cardx: insightsengineering.github.io/cardx
- riskmetric: pharmar.github.io/riskmetric
- 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.