QC and double programming with {diffdf}
Verifying clinical datasets and analysis results through independent derivations and tabular diffing
The problem
Unit tests compare output with a known answer (expect_equal(add(2, 2), 4)). A whole analysis dataset or summary table has no such oracle: nobody can hand-calculate every treatment-emergent flag, baseline value or imputed date across a study in advance.
Clinical reporting’s answer is independent double programming:
Raw / SDTM Data ──┬──> [Primary Programmer] ──> Production ADaM / TFL
│ │
│ Independent Cognition
│ │
└──> [Validation Programmer] ──> QC ADaM / TFL
│
▼
[Programmatic Reconciliation] ──> Clean Match
Two programmers independently write separate code from the written Statistical Analysis Plan (SAP) and dataset specifications. Neither programmer inspects the other’s code. Both run their programs against the same source data, and an automated comparison tool reconciles the outputs record by record.
What independent programming catches
Reviewing your own code tends to confirm your own assumptions; a second, independent implementation doesn’t share them. It catches:
- Specification ambiguity: If an SAP states that baseline is the “last non-missing assessment prior to study treatment”, does an assessment on Day 1 with no recorded timestamp count as baseline? Two independent programmers will make distinct interpretations. When their outputs diverge, the comparison surfaces the ambiguous specification before regulatory filing.
- Boundary and off-by-one errors: Subtle conditional logic errors, such as using
AGE <= 65instead ofAGE < 65, or computing study day without accounting for the absence of Day 0 in CDISC standards. - Filtering and language quirks: How missing values behave under filtering. In SAS, a missing numeric value is treated as smaller than any number, so
where AGE < 65keeps missing ages. In R,NA < 65isNA:dplyr::filter()drops those rows, whiledf[df$AGE < 65, ]returns a row ofNAs for each one. Independent implementations uncover these divergent assumptions. - Transcription errors: Miskeyed dictionary codes, cutoff values, or visit numbers.
The limits of double programming
Double programming is valuable, but it is not infallible. In a well-known 1986 experiment, Knight and Leveson had many programmers implement the same specification independently and found that their failures were correlated: independent programmers tend to trip over the same hard cases.
If the written specification contains an error—such as an incorrect formula or wrong population cutoff—both programmers will implement that error. The comparison will report no differences, creating false confidence. Double programming verifies conformance to interpretation, not clinical validity.
It also costs a second implementation for every output, so many teams use risk-based QC levels, spending the most effort where an error would matter most. A typical (illustrative) scheme:
| QC Level | Methodology | Scope |
|---|---|---|
| Level 1: Self-Check & Log Review | Primary programmer verifies execution logs (no warnings, errors, or unexpected conversions) and runs automated linters. | Exploratory tables, internal review dashboards, preliminary slides. |
| Level 2: Independent Code Review | A second programmer inspects the code against the SAP and performs spot checks on intermediate datasets. | Secondary safety listings, standard demographic tables where the underlying ADSL dataset is double-programmed. |
| Level 3: Independent Double Programming | Two independent programs and automated tabular diffing. | Primary and key secondary efficacy endpoints, core safety ADaM datasets (ADSL, ADAE), pivotal Clinical Study Report summary tables. |
The web analogue
Web teams use golden-file (snapshot) tests: generate an output file and diff it against an approved reference.
A text or byte diff (git diff, diff, checksums) is the wrong tool for data frames:
- Row and column order: the same records in a different order are the same data, but not the same bytes.
- Floating-point noise: summing in a different order can change a value in the 16th digit.
- Attributes: labels, factor levels and data frame classes (
tbl_dfversusdata.frame) don’t show up in a text diff at all.
What’s needed is a comparator that matches records by key and variables by name, compares numbers within a tolerance, checks attributes, and points to the exact cells that differ.
The R way
In legacy workflows, tabular reconciliation was performed in SAS using PROC COMPARE. In the modern R clinical ecosystem, the primary tool for semantic data frame comparison is {diffdf}.
{diffdf} compares two data frames and reports differences in columns, classes, attributes (such as variable labels) and values.
The core function: diffdf()
The primary comparison function is diffdf::diffdf():
library(diffdf)
dm <- pharmaversesdtm::dm
# Primary derivation: pooled age group with cutoff at 65
prod <- data.frame(
STUDYID = dm$STUDYID,
USUBJID = dm$USUBJID,
AGE = dm$AGE,
AGEGR1 = ifelse(dm$AGE < 65, "<65", ">=65"),
TRT01A = dm$ACTARM,
stringsAsFactors = FALSE
)
attr(prod$AGEGR1, "label") <- "Pooled Age Group 1"
# Validation derivation: planted boundary error (<= 65 instead of < 65)
qc_buggy <- data.frame(
STUDYID = dm$STUDYID,
USUBJID = dm$USUBJID,
AGE = dm$AGE,
AGEGR1 = ifelse(dm$AGE <= 65, "<65", ">=65"),
TRT01A = dm$ACTARM,
stringsAsFactors = FALSE
)
attr(qc_buggy$AGEGR1, "label") <- "Pooled Age Group 1"To compare the datasets, provide the two data frames and define the unique record identifier using keys:
diff_res <- diffdf(
base = prod,
compare = qc_buggy,
keys = "USUBJID",
suppress_warnings = TRUE
)
diffdf_has_issues(diff_res)Running diffdf_has_issues(diff_res) returns TRUE. If warnings are not suppressed, diffdf() also emits a warning summarizing the findings.
Key arguments in diffdf()
The function provides explicit parameters to control how strictly differences are evaluated:
keys(defaultNULL): A character vector naming the variables that uniquely identify each observation (for example,"USUBJID"in ADSL, orc("USUBJID", "PARAMCD", "AVISITN")in BDS datasets). Ifkeysis omitted,diffdf()falls back to comparing by row index. If keys contain duplicate values in either dataset,diffdf()stops with an informative error.tolerance(defaultsqrt(.Machine$double.eps)≈1.49e-08): The numeric comparison threshold. Two numbers count as equal if their absolute difference is withintolerance(divided byscalefirst, if you set one).scale(defaultNULL): an optional divisor, for relative rather than absolute differences.strict_numeric(defaultTRUE): IfTRUE, anintegercolumn compared with adoubleone is reported as a class difference (inVarClassDiffs). IfFALSE, integers are cast to double for comparison. Key variables are never cast.strict_factor(defaultTRUE): IfTRUE, comparing afactorto acharactercolumn is flagged as a class discrepancy. IfFALSE, factors are cast to characters for value comparison.check_column_order(defaultFALSE): When set toTRUE, verifies that matching columns appear in the exact same positional sequence.check_df_class(defaultFALSE): When set toTRUE, flags differences between data frame class tags (such as a tibble versus a basedata.frame).suppress_warnings(defaultFALSE): whenTRUE,diffdf()doesn’t also emit a warning when it finds differences (the report is unchanged).
Reading the report and isolating issue rows
Printing diff_res outputs a structured comparison report:
Differences found between the objects!
Summary of BASE and COMPARE
====================================
PROPERTY BASE COMP
------------------------------------
Name prod qc_buggy
Class data.frame data.frame
Rows(#) 306 306
Columns(#) 5 5
------------------------------------
Not all Values Compared Equal
=============================
Variable No of Differences
-----------------------------
AGEGR1 4
-----------------------------
======================================
VARIABLE USUBJID BASE COMPARE
--------------------------------------
AGEGR1 01-707-1206 >=65 <65
AGEGR1 01-709-1309 >=65 <65
AGEGR1 01-715-1107 >=65 <65
AGEGR1 01-715-1319 >=65 <65
--------------------------------------
The report identifies that four subjects differed in AGEGR1.
To programmatically inspect the problem rows in the original data, use diffdf::diffdf_issuerows():
issue_rows <- diffdf_issuerows(prod, diff_res, vars = "AGEGR1")
issue_rows[, c("USUBJID", "AGE", "AGEGR1", "TRT01A")] USUBJID AGE AGEGR1 TRT01A
1 01-707-1206 65 >=65 Placebo
2 01-709-1309 65 >=65 Xanomeline High Dose
3 01-715-1107 65 >=65 Xanomeline Low Dose
4 01-715-1319 65 >=65 Xanomeline High Dose
Every differing row has AGE == 65. The QC programmer implemented <= 65, whereas the production derivation implemented < 65.
Once the programmers review the specification and correct the QC derivation, the comparison runs clean:
qc_clean <- data.frame(
STUDYID = dm$STUDYID,
USUBJID = dm$USUBJID,
AGE = dm$AGE,
AGEGR1 = ifelse(dm$AGE < 65, "<65", ">=65"),
TRT01A = dm$ACTARM,
stringsAsFactors = FALSE
)
attr(qc_clean$AGEGR1, "label") <- "Pooled Age Group 1"
diff_clean <- diffdf(
base = prod,
compare = qc_clean,
keys = "USUBJID",
suppress_warnings = TRUE
)
diffdf_has_issues(diff_clean)diffdf_has_issues(diff_clean) returns FALSE, and printing diff_clean outputs No issues were found!.
The companion script scripts/qc-demo.R runs the same two rounds. Its datasets also carry SEX and RACE, so its printed summary shows seven columns. Note that dm holds all 306 subjects, including screen failures; the ARD example below uses the 254-subject safety population from ADSL.
What to agree before QC starts
Agree these before either programmer writes code, so the comparison finds logic differences rather than formatting ones:
- Frozen specification version: Lock the exact commit or version of the SAP, mock table shells, and dataset specifications.
- Primary keys: Agree on the natural record identifiers for each dataset domain. Without keys,
diffdf()must fall back to row indices, meaning a single extra row will cascade into differences across the entire dataset. - Calculation precision vs display rounding: Keep derived variables unrounded as double-precision numbers in analysis datasets. Reserve rounding for the display layer. Base R’s
round()sends a 5 to the even digit (IEC 60559:round(0.5)is 0,round(2.5)is 2), while SASROUNDrounds halves away from zero, so agree on explicit rounding helpers when the two programs use different languages. - Tolerance parameters: For continuous statistical outputs, agree on a numerical tolerance (for example
1e-6) to absorb floating-point representation differences.
Comparing Analysis Results Data as data
Earlier in this series, Analysis Results Data in R with {cards} and {cardx} explored how to decouple statistical calculations from layout rendering using {cards}.
Diffing rendered RTF or PDF tables as text produces false alarms from layout. Compare the Analysis Results Data (ARD) behind them instead:
library(cards)
adsl_sub <- pharmaverseadam::adsl[pharmaverseadam::adsl$SAFFL == "Y", ]
ard_primary <- ard_continuous(adsl_sub, variables = "AGE", by = "TRT01A")
ard_qc <- ard_continuous(adsl_sub, variables = "AGE", by = "TRT01A")
# Flatten list-columns into atomic vectors for diffdf
flatten_ard <- function(ard) {
df <- as.data.frame(ard)
data.frame(
variable = df$variable,
stat_name = df$stat_name,
arm = vapply(df$group1_level, as.character, character(1)),
stat = vapply(df$stat, as.numeric, numeric(1)),
stringsAsFactors = FALSE
)
}
ard_p_flat <- flatten_ard(ard_primary)
ard_q_flat <- flatten_ard(ard_qc)
ard_diff <- diffdf(
base = ard_p_flat,
compare = ard_q_flat,
keys = c("variable", "stat_name", "arm"),
tolerance = 1e-6,
suppress_warnings = TRUE
)
diffdf_has_issues(ard_diff){cards} objects store values in list-columns (stat, group1_level). Because diffdf() natively supports atomic vectors (numeric, character, logical), list-columns should be flattened or formatted before running diffdf(). Alternatively, deep object comparison tools such as waldo::compare() can compare nested list structures directly.
Once the underlying ARD compares with no differences, presentation engines ({rtables}, {tfrmt}, or {gt}) can render the numbers into CSR documents without recalculating metrics.
Documenting QC findings
Keep QC reviewable:
- Run logs and diff records: Save the text output of
diffdf()alongside the QC program execution logs in the study directory or analysis pipeline artifact repository. - Issue tracking: When a discrepancy occurs, document whether the root cause was a primary programming defect, a validation defect, or a specification ambiguity requiring SAP clarification.
- Traceability: keep the QC programs and the commits they ran against with the study records, so anyone can re-run a comparison later.
Companion code
Compares independent primary and QC derivations of ADSL variables using {diffdf}, demonstrating both an issue-flagged run with a planted defect and a clean comparison. Requires {diffdf} and {pharmaversesdtm}.
qc-demo.R
# qc-demo.R
# Independent double-programming demo comparing two derivations with {diffdf}.
#
# Run with:
# Rscript qc-demo.R
suppressPackageStartupMessages({
library(diffdf)
})
# Production derivation of a minimal ADSL-like dataset from SDTM DM.
derive_adsl_prod <- function(dm = pharmaversesdtm::dm) {
df <- data.frame(
STUDYID = dm$STUDYID,
USUBJID = dm$USUBJID,
AGE = dm$AGE,
AGEGR1 = ifelse(dm$AGE < 65, "<65", ">=65"),
SEX = dm$SEX,
RACE = dm$RACE,
TRT01A = dm$ACTARM,
stringsAsFactors = FALSE
)
attr(df$AGEGR1, "label") <- "Pooled Age Group 1"
attr(df$TRT01A, "label") <- "Actual Treatment Arm"
df
}
# QC derivation with a planted boundary discrepancy (<= 65 vs < 65).
derive_adsl_qc_buggy <- function(dm = pharmaversesdtm::dm) {
df <- data.frame(
STUDYID = dm$STUDYID,
USUBJID = dm$USUBJID,
AGE = dm$AGE,
AGEGR1 = ifelse(dm$AGE <= 65, "<65", ">=65"),
SEX = dm$SEX,
RACE = dm$RACE,
TRT01A = dm$ACTARM,
stringsAsFactors = FALSE
)
attr(df$AGEGR1, "label") <- "Pooled Age Group 1"
attr(df$TRT01A, "label") <- "Actual Treatment Arm"
df
}
# Fixed QC derivation resolving the discrepancy to match the specification.
derive_adsl_qc_clean <- function(dm = pharmaversesdtm::dm) {
df <- data.frame(
STUDYID = dm$STUDYID,
USUBJID = dm$USUBJID,
AGE = dm$AGE,
AGEGR1 = ifelse(dm$AGE < 65, "<65", ">=65"),
SEX = dm$SEX,
RACE = dm$RACE,
TRT01A = dm$ACTARM,
stringsAsFactors = FALSE
)
attr(df$AGEGR1, "label") <- "Pooled Age Group 1"
attr(df$TRT01A, "label") <- "Actual Treatment Arm"
df
}
# Reconcile primary and QC datasets using diffdf keyed by USUBJID.
compare_adsl <- function(
base,
compare,
keys = "USUBJID",
tolerance = sqrt(.Machine$double.eps)
) {
diffdf(
base = base,
compare = compare,
keys = keys,
suppress_warnings = TRUE,
tolerance = tolerance
)
}
if (sys.nframe() == 0L) {
dm <- pharmaversesdtm::dm
prod <- derive_adsl_prod(dm)
qc_buggy <- derive_adsl_qc_buggy(dm)
qc_clean <- derive_adsl_qc_clean(dm)
cat("=== Round 1: Primary vs QC with Planted Boundary Bug ===\n")
diff_round1 <- compare_adsl(prod, qc_buggy)
print(diff_round1)
cat(sprintf("Has issues: %s\n\n", diffdf_has_issues(diff_round1)))
cat("Issue rows subset from production dataset:\n")
print(diffdf_issuerows(prod, diff_round1, vars = "AGEGR1"))
cat("\n")
cat("=== Round 2: Primary vs Fixed QC ===\n")
diff_round2 <- compare_adsl(prod, qc_clean)
print(diff_round2)
cat(sprintf("Has issues: %s\n", diffdf_has_issues(diff_round2)))
}Sources
Package documentation
- diffdf: CRAN
- cards: pharmaverse.github.io/cards
- pharmaversesdtm: pharmaverse.github.io/pharmaversesdtm
- pharmaverseadam: pharmaverse.github.io/pharmaverseadam
- waldo: waldo.r-lib.org
Further reading
References worth reading alongside this post (official documents, linked for context rather than quoted line by line):
- Knight and Leveson, “An experimental evaluation of the assumption of independence in multiversion programming” (IEEE Transactions on Software Engineering, 1986): doi.org/10.1109/TSE.1986.6312924
- 2026-09-27: Added a Companion code section with the full script.