Analysis Results Data in R with {cards} and {cardx}

Separating statistical calculation from display logic through tidy, auditable results tables

How to build, manipulate, and quality-control Analysis Results Data (ARD) in R with cards and cardx, decoupling computations from presentation.
Published

2026-09-26

Modified

2026-09-27

The problem

In traditional clinical reporting workflows, statistical calculations are trapped inside presentation scripts. A single program reads an ADaM dataset, subsets the population, computes descriptive metrics, concatenates them into formatted strings like "75.2 (8.6)", and writes pagination control codes for an RTF document.

This coupling creates three recurring engineering bottlenecks:

  • Calculations cannot be re-used: A statistic computed for a baseline demographic table cannot be ingested by an executive slide deck, a patient profile listing, or an interactive Shiny safety dashboard. Each deliverable recalculates the metric independently, creating opportunities for divergent filtering or rounding.
  • Cross-table reconciliation requires manual archaeology: When the safety population count in Table 14.1.1 differs from the denominator in Table 14.3.1, programmers must trace through nested formatting macros to locate where derivation logic diverged.
  • Quality control diffs layout instead of data: In independent double-programming, verification often relies on comparing rendered RTF files. Programmers end up investigating false positives caused by line wrapping, font sizes, or cell margins rather than focusing on numerical differences.

When numbers are computed inside display code, they cease to exist as data.

The web analogue

Web development encountered this challenge when server-rendered pages embedded SQL queries directly inside HTML markup. Altering a visual component broke database queries, and sharing data across platforms required scraping HTML.

Modern web architectures resolved this by establishing strict data contracts:

Database Layer ──> [API Contract] ──> Structured Data ──> [Component Engine] ──> Presentation
  (ADaM Data)        (cards / cardx)     (Typed ARD / JSON)    (tbl_ard_summary/tfrmt)   (RTF / HTML)

In a decoupled web system:

  • The backend service exposes a typed API returning structured JSON. It provides raw numeric values and metadata, without styling, fonts, or page breaks.
  • Multiple clients consume the exact same payload: a web application, a mobile client, a dashboard, and a scheduled email alert.
  • Client teams update CSS and layout templates without touching backend logic.

Analysis Results Data (ARD) applies this exact pattern to clinical reporting. An ARD is an intermediate, typed dataset containing the calculated results of statistical analyses. Presentation engines consume the ARD to build formatted tables, but the calculations exist independently as auditable data.

The ARD shape: one row per statistic

In R, {cards} defines the standard data structure for Analysis Results Data. Rather than storing results in wide, ad-hoc tables, a {cards} object (an S3 data frame of class "card") stores results in a tidy structure where every row represents exactly one calculated statistic.

Here is what an ARD looks like when summarizing a continuous variable:

library(cards)
library(cardx)
library(gtsummary)

adsl_saf <- subset(pharmaverseadam::adsl, SAFFL == "Y")
adae_saf <- subset(pharmaverseadam::adae, SAFFL == "Y")

ard_age <- ard_continuous(adsl_saf, variables = AGE)
names(ard_age)

ard_age has the core columns: variable, context, stat_name, stat_label, stat, fmt_fun, warning and error. Grouped ARDs add group1/group1_level (and group2, … for nesting), and categorical ones add variable_level:

Column Type Role
variable character The variable being analyzed (for example "AGE").
variable_level list The level of a categorical variable (for example "F"); not present for continuous summaries.
group1, group1_level character, list Grouping variable name and value (for example TRT01A and "Placebo"). Repeated as group2, group3 for nested stratifications.
context character The analytical context generating the row (such as "continuous", "categorical", "dichotomous", or "stats_t_test").
stat_name character The machine-readable identifier for the statistic (such as "mean", "sd", "median", "p25", "n", "p").
stat_label character The human-readable label for display (such as "Mean", "SD", "Median", "Q1", "n", "%").
stat list The unrounded calculated statistic value. Stored in a list-column to hold diverse types (scalars, vectors, or test estimates).
fmt_fun list The formatting rule, represented as an integer specifying decimal places or a custom function.
warning list Warning condition objects captured during calculation, or NULL.
error list Error condition objects captured during calculation, or NULL.

Resilient computation with warning and error

A notable engineering feature of {cards} is how it handles calculation issues. In traditional monolithic scripts, an unhandled warning is buried in console logs, and an unexpected error crashes the entire reporting run.

In {cards}, every statistic calculation is wrapped in condition handlers. If a calculation produces a warning or error, {cards} records the condition object directly into the warning or error list-columns, assigns NULL to stat in the case of errors, and continues processing the remaining variables. You can audit all captured conditions across an ARD at any point:

cards::print_ard_conditions(ard_age)

This turns diagnostic evaluation into an inspectable data operation.

Building ARDs with {cards}

The {cards} package provides composable functions to build ARDs across clinical data types.

Univariate building blocks

You can generate individual summaries for continuous, categorical, and dichotomous variables:

# Continuous summary: N, mean, sd, median, p25, p75, min, max
ard_cont <- ard_continuous(adsl_saf, variables = AGE)

# Categorical tabulation: counts (n), denominators (N), and proportions (p)
ard_cat <- ard_categorical(adsl_saf, variables = SEX)

# Dichotomous summary: counts and rates for a single target level
ard_dich <- ard_dichotomous(
  adsl_saf,
  variables = SEX,
  value = list(SEX = "F")
)

Stacking tables with ard_stack()

In production reporting, tables combine multiple variables stratified by treatment arms, along with overall population summaries and total counts. Rather than calling individual functions and joining them by hand, ard_stack() compiles a complete study table ARD in a single pass:

ard_demo <- ard_stack(
  data = adsl_saf,
  ard_continuous(variables = AGE),
  ard_categorical(variables = SEX),
  .by = TRT01A,
  .overall = TRUE,
  .total_n = TRUE,
  .attributes = TRUE
)

unique(ard_demo$context)

The arguments to ard_stack() configure the clinical layout:

  • .by: The stratification variable (TRT01A), generating separate statistics for each treatment arm.
  • .overall = TRUE: Re-runs the calculations without stratification, adding an overall column.
  • .total_n = TRUE: Appends population counts from ard_total_n().
  • .attributes = TRUE: Extracts column labels from the input data frame via ard_attributes(), preserving CDISC variable labels for the display layer.

Hierarchical adverse events: ard_stack_hierarchical()

Adverse event tables require calculating nested participant incidences: first at the System Organ Class (SOC) level, and then for each Preferred Term (PT) within that SOC. A participant experiencing multiple occurrences of the same event should only be counted once in the numerator.

{cards} handles this with ard_stack_hierarchical():

ard_ae <- ard_stack_hierarchical(
  data = adae_saf,
  variables = c(AEBODSYS, AEDECOD),
  by = TRT01A,
  denominator = adsl_saf,
  id = USUBJID
)

By providing denominator = adsl_saf and id = USUBJID, ard_stack_hierarchical() dedupes adverse events per participant within each hierarchical level (AEBODSYS and AEDECOD) and divides by the safety population count for each treatment arm.

Statistical testing with {cardx}

Descriptive statistics cover baseline demographics, but regulatory tables and exploratory reports frequently require inferential statistics: p-values, confidence intervals, and hypothesis tests.

{cardx} extends {cards} by wrapping common statistical tests into ARD-generating functions:

# Pearson's chi-squared test across treatment arms
ard_chisq <- ard_stats_chisq_test(
  adsl_saf,
  by = TRT01A,
  variables = SEX
)

# Two-sample Welch t-test comparing two specific arms
adsl_2arms <- subset(adsl_saf, TRT01A %in% c("Placebo", "Xanomeline High Dose"))
ard_ttest <- ard_stats_t_test(
  adsl_2arms,
  by = TRT01A,
  variables = AGE
)

Because {cardx} functions return standard "card" data frames, they bind directly with descriptive ARDs using cards::bind_ard():

ard_combined <- bind_ard(ard_demo, ard_chisq)

The combined ARD contains both descriptive summaries and inferential test statistics, stored with their respective context, stat_name, and calculated stat values.

Working with an ARD

Once generated, an ARD can be formatted, filtered, extracted, or reshaped for downstream use.

Applying formatting functions

The stat column stores unrounded raw numbers. To prepare an ARD for tabular display, apply_fmt_fun() evaluates the formatting rule in fmt_fun and creates a stat_fmt column containing formatted character strings:

ard_formatted <- apply_fmt_fun(ard_demo)

If study requirements demand custom decimal precision (such as reporting means to two decimal places instead of one), you can update the formatting rules using update_ard_fmt_fun() prior to formatting:

ard_custom <- ard_demo |>
  update_ard_fmt_fun(stat_names = "mean", fmt_fun = 2) |>
  apply_fmt_fun()

Filtering and extracting statistics

Because an ARD is an S3 data frame, you can filter rows using standard dplyr::filter() without stripping the "card" class:

ard_filtered <- ard_demo |>
  dplyr::filter(stat_name %in% c("mean", "sd", "n", "p"))

To extract specific values into a named list—for example when inserting verified numbers into a narrative clinical report—use get_ard_statistics():

mean_age <- get_ard_statistics(
  ard_demo,
  variable %in% "AGE",
  stat_name %in% "mean"
)

Reshaping for review

While the one-row-per-statistic structure is ideal for computation and storage, human reviewers often prefer inspecting a flattened table. You can unflatten grouping levels and unnest statistics using tfrmt::shuffle_card() (which supersedes the deprecated cards::shuffle_ard()):

ard_flat <- tfrmt::shuffle_card(ard_demo, by = "TRT01A")

This returns a rectangular tibble where each treatment arm forms a column and statistics are unnested for straightforward visual scanning.

Quality control: comparing ARDs as data

Double-programming is the cornerstone of clinical quality control. In legacy workflows, comparing two programmers’ outputs involves comparing RTF or PDF documents. Differences in column widths, font metrics, or line wraps introduce noise that obscures genuine calculation discrepancies.

In an ARD-first workflow, the primary programmer and the validation programmer each produce an independent ARD. Quality control becomes a direct data comparison:

# Programmer 1 (Primary)
ard_p1 <- ard_stack(
  data = adsl_saf,
  ard_continuous(variables = AGE),
  ard_categorical(variables = SEX),
  .by = TRT01A
)

# Programmer 2 (Validation, with a discrepancy in Placebo mean age)
ard_p2 <- ard_stack(
  data = adsl_saf,
  ard_continuous(variables = AGE),
  ard_categorical(variables = SEX),
  .by = TRT01A
)
ard_p2$stat[[2]] <- 74.0

# Compare as data
waldo::compare(ard_p1, ard_p2)

waldo::compare() inspects the underlying list-columns element by element, immediately pinpointing that element [[2]] of the stat column differs (75.2 versus 74.0). It ignores cosmetic layout differences and flags only divergent data.

For teams that prefer structured difference tables, diffdf::diffdf() can compare flattened data frames produced after unnesting or running apply_fmt_fun().

Rendering one ARD several ways

Because the ARD represents verified data rather than presentation code, you can render it across different outputs without recomputing statistics:

tbl_rendered <- tbl_ard_summary(
  cards = ard_demo,
  by = TRT01A,
  label = list(AGE ~ "Age (Years)", SEX ~ "Sex")
)

gtsummary::tbl_ard_summary() consumes the pre-computed ARD directly. You can convert the resulting object to a {gt} table with gtsummary::as_gt(), export it to RTF with gt::gtsave(), or render it to HTML.

Similarly, {tfrmt} consumes pre-aggregated ARD tables and applies an external formatting shell, mapping columns, labels, and footnote plans without altering the calculated numbers.

Connection to the CDISC Analysis Results Standard (ARS)

Analysis Results Data in R aligns closely with wider industry efforts to standardize clinical analysis deliverables. The CDISC Analysis Results Standard (ARS) defines a machine-readable, vendor-neutral metadata model for describing planned analyses, their execution rules, and their final results.

It is important not to overclaim what {cards} does: {cards} provides an R-native tabular implementation of Analysis Results Data (a tidy data frame of class "card"), not a full CDISC ARS serializer. However, by decoupling statistical calculation from display and structuring every metric into standard columns (variable, context, stat_name, stat), {cards} prepares your clinical reporting pipeline for metadata-driven automation. The next post in this series explores the CDISC Analysis Results Standard (ARS) in detail.

The accompanying script scripts/ard-demo.R builds a demographics ARD and an adverse-event ARD (by system organ class and preferred term) from {pharmaverseadam} with {cards}, adds a treatment comparison with {cardx}, and shows how comparing two ARDs catches a planted discrepancy.

NoteComing up in the Pharma series

The next post explores the CDISC Analysis Results Standard (ARS) in depth, covering machine-readable analysis definitions and regulatory results metadata.

Companion code

View ard-demo.R · Download

Builds a demographics ARD and an adverse-event ARD with {cards}, adds a treatment comparison with {cardx}, and uses {waldo} to catch a planted discrepancy between independent runs. Requires {cards}, {cardx}, {pharmaverseadam}, and {waldo}.

# Analysis Results Data (ARD) with {cards} and {cardx}: a demographics ARD, an
# adverse-event ARD by system organ class and preferred term, a t-test, and a
# QC comparison that catches a planted discrepancy.
# Data: {pharmaverseadam} (example data, not real patients).
#
#   Rscript ard-demo.R

safety_adsl <- function() {
  subset(pharmaverseadam::adsl, SAFFL == "Y")
}

safety_adae <- function() {
  subset(pharmaverseadam::adae, SAFFL == "Y")
}

# Demographics: age and sex by actual treatment, plus an overall column.
demog_ard <- function(adsl) {
  cards::ard_stack(
    adsl,
    cards::ard_continuous(variables = AGE),
    cards::ard_categorical(variables = SEX),
    .by = TRT01A,
    .overall = TRUE
  )
}

# Adverse events: subjects counted once per SOC and per PT, with the safety
# population as the denominator.
ae_ard <- function(adae, adsl) {
  cards::ard_stack_hierarchical(
    adae,
    variables = c(AEBODSYS, AEDECOD),
    by = TRT01A,
    denominator = adsl,
    id = USUBJID
  )
}

# A treatment comparison: Welch two-sample t-test of age, two arms.
age_ttest_ard <- function(adsl, arms = c("Placebo", "Xanomeline High Dose")) {
  cardx::ard_stats_t_test(
    adsl[adsl$TRT01A %in% arms, ],
    by = TRT01A,
    variables = AGE
  )
}

# QC: an independent programmer's ARD, compared as data. waldo::compare()
# returns an empty result when the two agree.
compare_ards <- function(primary, qc) {
  waldo::compare(primary, qc, x_arg = "primary", y_arg = "qc")
}

# For the demo: the QC programmer's Placebo mean age is slightly off.
plant_discrepancy <- function(ard) {
  row <- which(
    ard$variable == "AGE" &
      ard$stat_name == "mean" &
      vapply(ard$group1_level, function(x) identical(x, "Placebo"), logical(1))
  )
  ard$stat[[row]] <- ard$stat[[row]] + 0.5
  ard
}

# Run only when called as a script (not when sourced by the tests).
if (sys.nframe() == 0L) {
  adsl <- safety_adsl()
  demog <- demog_ard(adsl)
  print(demog[demog$stat_name %in% c("N", "mean", "n", "p"), ])
  ae <- ae_ard(safety_adae(), adsl)
  message(nrow(ae), " rows in the adverse-event ARD")
  tt <- age_ttest_ard(adsl)
  print(tt[tt$stat_name %in% c("estimate", "p.value"), c("stat_name", "stat")])
  message("QC, independent re-run:")
  print(compare_ards(demog, demog_ard(adsl)))
  message("QC, with a planted discrepancy:")
  print(compare_ards(demog, plant_discrepancy(demog_ard(adsl))))
}

Sources

Standards

Package documentation

NoteUpdates
  • 2026-09-27: Added a Sources section.
  • 2026-09-27: Added a Companion code section with the full script.