Validation-ready R packages
Risk-based package qualification, {riskmetric}, and auditable evidence for regulated clinical reporting
The problem
When statistical programmers assemble an R clinical reporting pipeline—such as the pipelines described in our posts on the clinical reporting pipeline, generating TFLs, Analysis Results Data with {cards}, and the CDISC Analysis Results Standard and {siera}—they depend on a deep tree of open-source packages.
Introducing a new package inevitably prompts a familiar gatekeeping query: “Is this package validated?”
In regulated environments, that question creates two failure modes:
- The blanket ban: Teams restrict environments to base R and legacy tools, refusing modern packages without an external compliance stamp. Programmers then write bespoke derivation scripts that re-introduce the very errors modern packages prevent.
- The passive rubber-stamp: Teams assume that because a package is on CRAN, it is automatically acceptable for primary clinical endpoints.
Both approaches stem from a fundamental misunderstanding: “validated package” is a misnomer.
An R package cannot be validated in the abstract. Under regulatory standards—including the US FDA’s General Principles of Software Validation (2002) and GAMP 5—software validation establishes objective evidence that software conforms to user needs and intended uses within a qualified infrastructure. A function might be suitable for exploratory visualisation, yet require rigorous verification if used to derive a primary study endpoint.
CRAN technical checks verify that packages build, execute examples, and pass basic checks across platforms. CRAN does not evaluate statistical accuracy or suitability for regulatory reporting.
Teams need an engineered, risk-based approach to determine whether an open-source package is validation-ready and fit for its intended use.
The web analogue: dependency vetting and scorecards
Modern web engineering and DevSecOps encountered this challenge years ago. A typical web service depends on many third-party libraries across deep dependency trees. Manually inspecting every line of source code is impossible.
Instead of binary trust or manual reviews, modern software engineering relies on automated heuristic risk scoring and transparent supply chain metadata:
- OpenSSF Scorecard (scorecard.dev): An open-source tool from the Open Source Security Foundation (OpenSSF). It evaluates Git repositories against automated heuristic checks—active maintenance, code review requirements, branch protection, CI test execution, and pinned dependencies—returning an objective score from 0 to 10.
- Software Bill of Materials (SBOM): Machine-readable manifests (CycloneDX, SPDX) document dependency trees, cryptographic hashes, and licences, paired with vulnerability scanners (
npm audit,pip-audit) to detect security defects. - Curated internal registries: Enterprise organisations route dependencies through internal artifact repositories after automated policy checks rather than allowing direct production downloads.
This engineering pattern replaces subjective intuition with reproducible, automated metrics.
The R Validation Hub framework
The R Validation Hub (pharmar.org), which describes itself as an R Consortium-funded ISC working group, set out a risk-based approach in its white paper, “A Risk-based Approach for Assessing R package Accuracy within a Validated Infrastructure”. In short:
1. Core packages and contributed packages
The white paper separates two kinds of package:
- Base and recommended (“core”) packages: developed by the R Foundation and shipped with the basic R installation.
- Contributed packages: “developed by anyone, and may differ in accuracy”, so they are where assessment effort goes.
2. Four criteria for contributed packages
For contributed packages, the white paper looks at:
- Purpose: does the package do statistical work, or not?
- Maintenance good practice: signs of a software development life cycle (versioning, NEWS, bug reporting, documentation).
- Community usage: how widely the package is used and exposed to scrutiny.
- Testing: unit tests and test coverage.
Separately from those metrics, the consequence of an error depends on intended use: a package that computes a primary efficacy analysis deserves more scrutiny than one that formats a table caption.
3. “Intended for Use” versus “Imports”
The white paper distinguishes packages that analysts load directly (“Intended for Use”) from the dependencies they bring in (“Imports”), and says accuracy only needs to be verified for the Intended for Use packages; the imports are exercised through them.
Quantifying package risk with {riskmetric}
To gather these metrics automatically, the R Validation Hub developed {riskmetric}.
The package workflow operates across three main stages:
library(riskmetric)
library(dplyr)
# 1. Create package references
pkgs <- c("glue", "cards", "riskmetric")
refs <- pkg_ref(pkgs, source = "pkg_install")The pkg_ref() function inspects local libraries or remote repositories without altering package files. Setting source = "pkg_install" targets the currently installed package in the active library.
The assessment catalog
Running pkg_assess() executes assessment functions that gather objective metadata:
# Define offline assessments that require no external network calls
offline_assessments <- list(
has_news = riskmetric::assess_has_news,
news_current = riskmetric::assess_news_current,
has_vignettes = riskmetric::assess_has_vignettes,
export_help = riskmetric::assess_export_help,
has_website = riskmetric::assess_has_website,
has_maintainer = riskmetric::assess_has_maintainer,
has_source_control = riskmetric::assess_has_source_control,
has_bug_reports_url = riskmetric::assess_has_bug_reports_url,
has_examples = riskmetric::assess_has_examples,
dependencies = riskmetric::assess_dependencies,
license = riskmetric::assess_license
)
assessed <- pkg_assess(refs, assessments = offline_assessments)In {riskmetric} 0.2.7, nineteen assessment functions evaluate different facets of package quality:
- Local installation metrics (offline):
assess_has_news,assess_news_current,assess_has_vignettes,assess_export_help(documentation proportion),assess_has_examples,assess_has_maintainer,assess_has_website,assess_has_source_control,assess_has_bug_reports_url,assess_dependencies(dependency footprint),assess_size_codebase,assess_exported_namespace, andassess_license. - Remote network metrics:
assess_downloads_1yr(queries CRAN download logs),assess_last_30_bugs_status(queries GitHub/GitLab issue resolution ratios),assess_remote_checks(queries CRAN check farm results), andassess_reverse_dependencies. - Source-dependent metrics:
assess_covr_coverage(requires package source code to runcovr::package_coverage()) andassess_r_cmd_check(results from runningR CMD check).
The demo below uses only offline metrics that work on an installed package. It leaves out assess_size_codebase and assess_exported_namespace, which attach the package’s namespace (a side effect on the search path) and can fail to score on binary installs.
The scoring engine
Calling pkg_score() maps raw assessment data into standardised numeric scores between 0 and 1:
scored <- pkg_score(assessed)Understanding how {riskmetric} scores packages is essential:
- Individual metric scores: Each assessment is evaluated by a specialised
metric_scoreS3 method. These methods measure quality (where 1 indicates high quality and 0 indicates low quality). For example,export_helpcalculates the proportion of documented exported objects, anddependenciesapplies a logistic penalty to large dependency footprints. Thelicenseassessment returnsNA_real_by design, because license acceptability reflects organisational legal policy rather than a mathematical score. - Aggregate risk score: The
summarize_scores()function standardises non-negative weights across metrics, calculates the weighted quality score, and returns overall package risk as Risk = 1 − Quality.
In {riskmetric}, 0 represents lowest risk (highest quality) and 1 represents highest risk.
We can classify packages into transparent risk categories based on a documented threshold rule:
classify_risk <- function(score, low_threshold = 0.25, medium_threshold = 0.50) {
ifelse(
is.na(score),
"Unassessed",
ifelse(
score <= low_threshold,
"Low Risk",
ifelse(score <= medium_threshold, "Medium Risk", "High Risk")
)
)
}
summary_table <- scored |>
mutate(decision = classify_risk(pkg_score)) |>
select(
package,
version,
pkg_score,
decision,
has_news,
news_current,
export_help,
has_vignettes,
dependencies,
license
)
as.data.frame(summary_table)Running this offline against our local environment yields:
{glue}(score ~ 0.107): Low Risk, driven by comprehensive documentation, low dependencies, and active maintainership.{cards}(score ~ 0.272): Medium Risk, driven by its larger dependency footprint despite complete function documentation.{riskmetric}(score ~ 0.273): Medium Risk, reflecting its dependency footprint and the absence of a current version entry in its NEWS file.
Governance and triage with {riskassessment}
While {riskmetric} provides the programmatic engine, organisations require a collaborative interface for team reviews, sign-offs, and audits. The R Validation Hub developed {riskassessment}, an open-source Shiny application designed specifically for this workflow.
According to its documentation, the app lets reviewers:
- look at
{riskmetric}output without writing R code; - add comments on individual metrics and give each package an overall assessment (low, medium or high risk);
- download a static report with the package’s risk, metric outputs and the reviewer’s summary and comments;
- store assessments in a database for later viewing.
An admin user can manage users, change the metric weights used in the risk score, and define decision categories and automation rules based on risk scores. The app has several predefined roles beyond admin (see its “User Roles and Privileges” documentation).
What evidence a regulated team keeps
A risk-based approach does not eliminate documentation; it replaces unstructured speculation with auditable engineering artifacts. For any package used in clinical reporting, a regulated team retains five pieces of evidence:
- The assessment report: The static report generated by
{riskmetric}or{riskassessment}capturing metric scores, reviewer comments, and the final risk classification. - The pinned environment lockfile: An immutable
renv.lockrecording exact package versions, a hash for each package, and repository sources (such as a dated Posit Package Manager snapshot), as covered in our post on dependencies, runtime pinning and vetting. - Execution environment qualification: A container image (Docker/OCI) or controlled server image verifying that system compilers, OS libraries, and BLAS/LAPACK runtimes match the tested environment.
- Installation and test runs in the target environment: CI runs showing that every declared package loads and that your own tests (and, where useful, the packages’ tests) pass in the environment you will use.
- Documented intended use: A written statement in the project specification explaining what role the package plays in the reporting pipeline and confirming its fitness for that designated purpose.
Companion code
View riskmetric-demo.R · Download
A modular, runnable implementation of this offline assessment workflow. It inspects installed packages in the local library, applies offline quality metrics, computes composite risk scores, and outputs a formatted decision table. Requires {riskmetric} and {dplyr}.
The script’s paired test file verifies that package references are generated correctly, that scores fall within the valid [0, 1] range, and that classification rules execute without requiring external network connectivity.
riskmetric-demo.R
# Assess installed R packages offline with {riskmetric}
#
# Runs local, network-free risk assessments against installed packages in the
# active library, scores quality metrics, and classifies packages into
# risk categories based on a documented threshold rule.
#
# Run with:
# Rscript riskmetric-demo.R
suppressPackageStartupMessages({
library(riskmetric)
library(dplyr)
})
#' Return a list of assessment functions that execute offline
#'
#' Selects assessments from {riskmetric} that inspect local installation
#' directories and DESCRIPTION metadata without querying remote APIs (such as
#' CRAN check servers, GitHub issue trackers, or download logs).
#'
#' @return A named list of assessment functions.
offline_assessments <- function() {
list(
has_news = riskmetric::assess_has_news,
news_current = riskmetric::assess_news_current,
has_vignettes = riskmetric::assess_has_vignettes,
export_help = riskmetric::assess_export_help,
has_website = riskmetric::assess_has_website,
has_maintainer = riskmetric::assess_has_maintainer,
has_source_control = riskmetric::assess_has_source_control,
has_bug_reports_url = riskmetric::assess_has_bug_reports_url,
has_examples = riskmetric::assess_has_examples,
dependencies = riskmetric::assess_dependencies,
license = riskmetric::assess_license
)
}
#' Assess installed packages without network access
#'
#' @param pkgs Character vector of installed package names.
#' @param assessments Named list of assessment functions. Defaults to
#' offline assessments.
#' @param lib_loc Optional library path. Defaults to `.libPaths()[1]`.
#'
#' @return A tibble of scored assessments with package metadata and
#' an aggregate `pkg_score` column.
assess_installed_packages <- function(
pkgs,
assessments = offline_assessments(),
lib_loc = NULL
) {
if (length(pkgs) == 0L) {
stop("At least one package name must be provided.")
}
refs <- riskmetric::pkg_ref(
pkgs,
source = "pkg_install",
lib.loc = lib_loc
)
assessed <- riskmetric::pkg_assess(refs, assessments = assessments)
riskmetric::pkg_score(assessed)
}
#' Classify a numeric risk score against organizational thresholds
#'
#' In {riskmetric}, risk ranges from 0 (lowest risk / highest quality)
#' to 1 (highest risk / lowest quality).
#'
#' @param score Numeric risk score in [0, 1] or NA.
#' @param low_threshold Numeric upper bound for low risk (inclusive).
#' @param medium_threshold Numeric upper bound for medium risk (inclusive).
#'
#' @return A character vector of risk categories: "Low Risk", "Medium Risk",
#' "High Risk", or "Unassessed".
classify_risk <- function(
score,
low_threshold = 0.25,
medium_threshold = 0.50
) {
ifelse(
is.na(score),
"Unassessed",
ifelse(
score <= low_threshold,
"Low Risk",
ifelse(score <= medium_threshold, "Medium Risk", "High Risk")
)
)
}
#' Summarise scored packages into a decision table
#'
#' @param scored_tbl Tibble returned by `assess_installed_packages()`.
#' @param low_threshold Numeric upper bound for low risk.
#' @param medium_threshold Numeric upper bound for medium risk.
#'
#' @return A tibble with package identity, risk score, decision category,
#' and selected individual metric scores.
summarise_package_risks <- function(
scored_tbl,
low_threshold = 0.25,
medium_threshold = 0.50
) {
scored_tbl |>
dplyr::mutate(
decision = classify_risk(
.data$pkg_score,
low_threshold = low_threshold,
medium_threshold = medium_threshold
)
) |>
dplyr::select(
"package",
"version",
"pkg_score",
"decision",
"has_news",
"news_current",
"export_help",
"has_vignettes",
"dependencies",
"license"
)
}
#' Run the complete offline risk assessment demonstration
#'
#' @param pkgs Character vector of installed packages to evaluate.
#' Defaults to three packages from the local library: glue, cards, riskmetric.
#'
#' @return A tibble containing the scored assessment and decision table.
run_riskmetric_demo <- function(pkgs = c("glue", "cards", "riskmetric")) {
scored <- assess_installed_packages(pkgs)
summarise_package_risks(scored)
}
if (sys.nframe() == 0L) {
message("Assessing installed packages offline with {riskmetric}...")
results <- run_riskmetric_demo()
print(as.data.frame(results))
}Sources
Standards and organisations
- R Validation Hub: pharmar.org
- R Validation Hub white paper (A Risk-based Approach for Assessing R package Accuracy within a Validated Infrastructure, Nicholls, Bargo & Sims, 2020): pharmar.org/white-paper
- GAMP 5 (2nd Edition): ispe.org
- OpenSSF Scorecard: scorecard.dev
Package documentation
- riskmetric: pharmar.github.io/riskmetric
- riskassessment: pharmar.github.io/riskassessment
- dplyr: dplyr.tidyverse.org
Further reading
References worth reading alongside this post (official documents, linked for context rather than quoted line by line):
- FDA, General Principles of Software Validation (guidance, 2002): fda.gov
- FDA, Statistical Software Clarifying Statement (6 May 2015, PDF): fda.gov
- 2026-09-27: Added a Companion code section with the full script.