The CDISC Analysis Results Standard and {siera}
Turning study analysis definitions into machine-readable metadata and auditable R code
The problem
In traditional clinical trial reporting, the blueprint for study deliverables is fragmented across disconnected documents. A Statistical Analysis Plan (SAP) specifies endpoints and populations in narrative prose. Table shells mock up visual displays in word-processor or spreadsheet documents. Statistical programmers then translate those descriptions into procedural macros or bespoke R scripts.
This manual translation creates three recurring engineering bottlenecks:
- Analysis definitions are scattered: To verify why a specific adverse-event table applied a certain treatment-emergent definition or population filter, a programmer must search through narrative paragraphs in the SAP, check footnotes in the table shell, and inspect extensive procedural code.
- Results are trapped in presentation documents: As noted in our posts on the clinical reporting pipeline and generating TFLs, clinical outputs are traditionally rendered directly to static Rich Text Format (RTF) or PDF files. Because numbers are embedded in display formatting, downstream systems—such as executive summaries, clinical dashboards, or meta-analyses—cannot programmatically ingest or verify results without scraping text.
- Cross-table reconciliation is error-prone: Table 14.1.1 (demographics) and Table 14.3.1 (safety) often independently re-derive denominator counts. Small divergences in filtering rules or rounding logic create discrepancies that require manual investigation.
Analysis Results Data with {cards} addresses the output side of this equation by storing computed statistics in a tidy, one-row-per-statistic tabular structure. But someone still has to write the bespoke R script that invokes each calculation. What clinical engineering requires is an open, machine-readable standard for the analysis plan itself.
The web analogue: contract-first code generation
In distributed systems and web API development, interface definitions once suffered from the same documentation drift. Teams wrote API specifications in wikis or PDF documents, while backend and frontend developers manually implemented route handlers, parameter validation, and client HTTP requests. When an endpoint or parameter changed, implementations silently diverged.
Web engineering resolved this by adopting contract-first specifications, epitomised by OpenAPI (formerly Swagger) and Protocol Buffers:
API Contract (OpenAPI JSON/YAML)
│
├──> Code Generator ──> Typed Client SDKs (TypeScript / Go / Python)
├──> Code Generator ──> Server Route Stubs & Input Validators
└──> Test Harness ──> Automated Contract & Schema Tests
In a contract-first architecture:
- The specification is the single source of truth: Endpoints, data types, query parameters, and response schemas are declared in a structured, machine-readable format.
- Boilerplate code is generated, not hand-coded: Tooling ingests the schema to generate typed client SDKs and server stubs. Programmers do not write repetitive data fetching or schema validation code by hand.
- Automated verification guards against divergence: Contract-testing tools verify that API responses conform to the specification on every build.
Applying this pattern to clinical reporting means treating analysis plans as machine-readable contracts. Instead of hand-coding every table script from prose requirements, teams define analyses in a structured standard and generate auditable execution code.
The R way: CDISC ARS and {siera}
The Clinical Data Interchange Standards Consortium (CDISC) established the Analysis Results Standard (ARS); v1.0 was published on 19 April 2024. The ARS establishes a technology-independent logical data model for describing planned analyses, their input data sources, populations, calculation methods, and results.
The CDISC ARS logical data model
At the top level of the ARS model is the ReportingEvent, which encapsulates all analyses and displays planned for a clinical milestone (such as a Clinical Study Report or interim analysis). Within a reporting event, the model organizes analysis metadata into distinct, linked entities:
| Model Entity | Purpose in the ARS Model | Clinical Example |
|---|---|---|
Output |
Defines a display item (table, listing, or figure) | Table 14-1.1: Demographics and Baseline Characteristics |
Analysis |
The core unit linking data, population, and method | Summary of Age in the Safety Population by Treatment Arm |
AnalysisSet |
Defines population inclusion criteria via logical conditions | Safety Population (SAFFL == "Y") |
DataSubset |
Defines analysis-specific record filtering rules | Treatment-emergent events (TRTEMFL == "Y") |
GroupingFactor |
Defines stratification factors (data-driven or categorized) | Actual Treatment Arm (TRT01A), Age Groups (AGEGR1) |
AnalysisMethod |
Describes the statistical algorithm and required operations | Summary statistics for continuous variables (n, mean, sd) |
An AnalysisMethod in the ARS model can define an Operation (one of the method’s computational steps; the generated ARD’s operationid points back to it) and an operational code template: AnalysisProgrammingCodeTemplate with its TemplateCodeParameters. These templates supply parameterized expressions that an execution engine populates with metadata variables (such as substituting TRT01A for grouping and AGE for the analysis variable).
How ARS relates to ARD and {cards}
The relationship between the CDISC Analysis Results Standard and Analysis Results Data (ARD) is a separation of metadata from tabular results:
- ARS is the specification contract: It defines what analyses exist, which populations and subsets apply, and how calculations are performed. It is vendor-neutral and technology-independent: the model itself names no storage format; tools exchange it as JSON (the format {siera} reads), and {siera} also reads the ARS Excel template.
- ARD is the tabular result: It represents the calculated numerical outputs: one row per statistic, containing values, parameter names, and condition flags.
{cards}is the R engine: It provides an R-native S3 data structure ("card") for calculating and storing ARD, with composable functions likecards::ard_continuous(),cards::ard_categorical(), andcards::ard_stack().
The ARS specification defines the analysis plan. An execution engine consumes that plan, executes {cards} calls against ADaM data, and produces an ARD.
Ingesting ARS and generating code with {siera}
The {siera} package (available on CRAN) bridges the CDISC ARS standard and R execution. It ingests ARS metadata—formatted in JSON or Excel—and generates executable R scripts that produce {cards}-compatible ARD datasets.
The core function in {siera} is siera::readARS(). The demo uses the package’s bundled example data: ARS_example("exampleARS_1.json") against the bundled ADSL.csv (84/84/86 subjects across the three TRT01AN arms in An_01), not pharmaverseadam::adsl used in earlier posts.
library(siera)
# Ingest bundled CDISC ARS JSON metadata
ars_file <- siera::ARS_example("exampleARS_1.json")
out_dir <- tempfile("siera_demo_")
dir.create(out_dir)
# Copy example ADaM dataset to the input folder
file.copy(siera::ARS_example("ADSL.csv"), file.path(out_dir, "ADSL.csv"))
# Generate R scripts from the ARS specification.
# readARS() writes the scripts to output_path and returns NULL, so its
# return value is not what you inspect - list the generated files instead.
siera::readARS(
ARS_path = ars_file,
output_path = out_dir,
adam_path = out_dir
)
basename(list.files(out_dir, pattern = "[.]R$"))siera::readARS() accepts:
ARS_path: Path to an ARS metadata file in JSON or Excel format.output_path: Directory where generated.Rscript files will be written (defaults totempdir()).adam_path: Directory where input ADaM datasets reside.spec_output: An optional output ID to generate code for a single display rather than all displays in the file.
{siera} also provides helper utilities: siera::ARS_example() lists or retrieves bundled ARS metadata files, and siera::ARD_script_example() accesses reference generated scripts.
Verifying and running generated scripts
Because {siera} emits standard R scripts, you can inspect and parse them using base R before execution:
# Verify that generated scripts parse without syntax errors
script_path <- file.path(out_dir, "ARD_Out_01.R")
parsed_code <- parse(file = script_path)
length(parsed_code)To run the generated script, execute it in an isolated environment pointing to your verified ADaM datasets. The generated code calls library() on its own dependencies (dplyr, readxl, readr, cards, cardx, broom, parameters, tidyr), so the project must have them installed — this site’s renv does:
# Execute the generated script in an isolated environment
env <- new.env(parent = globalenv())
sys.source(script_path, envir = env)
ard <- env$ARD
dim(ard)The resulting ard object is a complete Analysis Results Dataset:
# Inspect the ARD: both cards statistical values and ARS metadata keys
ard_sample <- ard[
ard$AnalysisId == "An_01",
c("variable", "stat_name", "stat", "AnalysisId", "MethodId", "OutputId")
]
ard_sampleCrucially, {siera} does not merely generate standard {cards} calls; it stamps CDISC ARS metadata columns directly onto each row:
# The generated ARD links directly to the CDISC ARS metadata IDs
unique(ard$AnalysisId)Each row records its AnalysisId, MethodId, OutputId, and operationid, establishing complete traceability from result to specification.
Anatomy of a generated script
Understanding how {siera} structures generated code is essential for code review. ARD_Out_01.R follows a consistent layout, visible in its own comments:
# Programme: Generate code to produce ARD for Out_01
# Output: Subject Disposition
# Date created: <timestamp>
# load libraries ----
library(dplyr)
...
# Load ADaM -------
ADSL <- readr::read_csv(...)
# Analysis An_01----
# Apply Analysis Set ---
# Apply Data Subset ---
# Apply Method ---
# Method ID: Mth_01
# Method name: Count by group for a categorical variable
# Method description: Count across groups for a categorical variable, ...
... (repeated per analysis in the output: An_01, An_02, ...)
# combine analyses to create ARD ----
ARD <- dplyr::bind_rows(df3_An_01, df3_An_02, ...)
Reviewing generated code in production
When incorporating generated reporting scripts into a clinical repository, teams should adopt specific engineering review practices:
- The metadata is the source of truth: Treat generated
.Rfiles like compiled build artifacts. If an analysis filter or grouping is incorrect, update the ARS metadata file and re-runsiera::readARS(). Never manually patch generated scripts in place; manual edits decouple code from metadata and invalidate traceability. - Automate syntax verification in CI: In CI pipelines, run
parse(file = script)across all generated files. This confirms that all parameterized metadata substitutions yielded valid R expressions before executing long-running calculations. - Double-programming as data comparison: Rather than having a second programmer independently write duplicate table formatting code, have the validation programmer independently derive the ARD. Compare the primary and validation ARDs as data frames using
waldo::compare(), as demonstrated in our ARD post.
Traceability and GxP qualification
In regulated clinical environments, open-source R packages are never qualified off the shelf. Package qualification is a formal, risk-based process conducted by a sponsor or team to demonstrate that software reliably fulfills its intended use in a controlled environment.
What CDISC ARS and {siera} provide is structural traceability:
- From Result to Method: Every calculated statistic in the ARD contains
MethodIdandoperationid, identifying the mathematical algorithm and operational step that produced it. - From Method to Analysis: The
AnalysisIdlinks the result to the exact planned analysis in the ARS metadata, identifying the target variable, population criteria, and stratification factors. - From Analysis to Output: The
OutputIdlinks the result to the planned display it belongs to. The model can also hold document references (ReferenceDocument,DocumentReference) for linking an output or analysis back to a SAP section or CSR table shell, though the bundled example JSON ships this list empty, so that link depends on what a sponsor’s own ARS file populates.
Each result row carries IDs that lead back to its analysis and method in the metadata, so a reviewer can follow a number back to its definition.
The post script scripts/ars-demo.R ingests CDISC ARS JSON metadata, generates R scripts into a temporary directory, parses each file for syntax integrity, and executes a generated script on ADaM data to produce a metadata-stamped ARD.
Pitfalls
- Manually editing generated scripts: Modifying generated
.Rscripts directly to resolve minor formatting issues destroys the link between metadata and execution code. All modifications must originate in the ARS specification. - ADaM naming discrepancies: ARS metadata expects specific variable names (such as
TRT01ANorSAFFL). If input ADaM datasets use non-standard column names or missing flags, generated scripts fail during column selection or filtering. - Incomplete ARS metadata sections: Removing a required top-level section (
analysisSets, in a copy of the bundled example) does not stop at a parsing error or a silent fallback to unfiltered data:readARS()emits a warning (“Input ARS file is missing required metadata sections: analysisSets”) and writes no.Rscripts at all. Check for that warning, and checkoutput_pathfor the expected script count, rather than assuming generation succeeded. - Confusing code generation with statistical review: Generating code from metadata automates the mechanical construction of R syntax, but does not verify whether the statistical method chosen in the SAP is clinically appropriate. Scientific and statistical review remains essential.
Companion code
Ingests CDISC ARS JSON metadata, generates R analysis scripts into a temporary directory, parses each file for syntax integrity, and executes a generated script on ADaM data to produce a metadata-stamped ARD. Requires {siera}, plus the packages the generated code loads: {dplyr}, {readxl}, {readr}, {cards}, {cardx}, {broom}, {parameters} and {tidyr}.
ars-demo.R
# Ingest CDISC Analysis Results Standard (ARS) metadata with {siera},
# generate R analysis programs, parse them for syntax correctness, and execute
# an auto-generated script to produce Analysis Results Data (ARD).
#
# Rscript ars-demo.R
# Ingest an ARS metadata file and generate R analysis scripts into output_dir.
generate_ars_scripts <- function(
ars_file = NULL,
output_dir = tempdir(),
adam_dir = tempdir(),
spec_output = ""
) {
if (is.null(ars_file)) {
ars_file <- siera::ARS_example("exampleARS_1.json")
}
siera::readARS(
ARS_path = ars_file,
output_path = output_dir,
adam_path = adam_dir,
spec_output = spec_output
)
list.files(output_dir, pattern = "[.]R$", full.names = TRUE)
}
# Parse a set of R script files to confirm each parses without syntax errors.
parse_ars_scripts <- function(script_paths) {
parsed <- lapply(script_paths, function(path) {
parse(file = path)
})
names(parsed) <- basename(script_paths)
parsed
}
# Execute a generated ARD script in an isolated environment. The generated
# code calls library() on its own dependencies (dplyr, readxl, readr, cards,
# cardx, broom, parameters, tidyr), so the project must have them installed.
run_generated_ard <- function(script_path) {
env <- new.env(parent = globalenv())
sys.source(script_path, envir = env)
env$ARD
}
# Verify that an ARD object contains core {cards} columns and CDISC ARS columns.
verify_ard_columns <- function(ard) {
cards_cols <- c("variable", "context", "stat_name", "stat")
ars_cols <- c("AnalysisId", "MethodId", "OutputId", "operationid")
all(c(cards_cols, ars_cols) %in% names(ard))
}
# Run only when called as a script (not when sourced by tests).
if (sys.nframe() == 0L) {
work_dir <- tempfile("ars_demo_")
dir.create(work_dir)
# Copy bundled example ADaM dataset to the working folder
file.copy(siera::ARS_example("ADSL.csv"), file.path(work_dir, "ADSL.csv"))
ars_path <- siera::ARS_example("exampleARS_1.json")
message("Ingesting ARS metadata: ", basename(ars_path))
scripts <- generate_ars_scripts(
ars_file = ars_path,
output_dir = work_dir,
adam_dir = work_dir
)
message("Generated ", length(scripts), " scripts:")
for (s in scripts) {
message(" - ", basename(s))
}
message("\nParsing generated scripts:")
parsed_exprs <- parse_ars_scripts(scripts)
for (name in names(parsed_exprs)) {
message(
" - ",
name,
": ",
length(parsed_exprs[[name]]),
" expressions parsed"
)
}
target_script <- scripts[1]
message("\nExecuting ", basename(target_script), "...")
ard <- run_generated_ard(target_script)
message("Execution complete. ARD dimensions: ", nrow(ard), " x ", ncol(ard))
message("CDISC ARS and {cards} columns present: ", verify_ard_columns(ard))
cols_to_show <- intersect(
c(
"variable",
"variable_level",
"stat_name",
"stat",
"AnalysisId",
"OutputId"
),
names(ard)
)
print(head(ard[, cols_to_show]))
}Sources
Standards
- CDISC Analysis Results Standard (v1.0, published 19 April 2024): cdisc.org/standards/foundational/analysis-results-standard
- ARS model documentation: cdisc-org.github.io/analysis-results-standard
Package documentation
- siera: CRAN
- cards: pharmaverse.github.io/cards
- 2026-09-27: Added a Sources section.
- 2026-09-27: Added a Companion code section with the full script.
- 2026-09-27: Listed every package the companion script needs, including those its generated code loads.