# 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])) }