# One demographics summary, three ways: {rtables} + {tern}, {gtsummary}, and # an Analysis Results Data (ARD) set from {cards} rendered with # gtsummary::tbl_ard_summary(). Then writes the gtsummary table to RTF. # Data: {pharmaverseadam} ADSL (example data, not real patients). # # Rscript tfl-demo.R # Safety population, with factors so every table shows the same levels. safety_adsl <- function(adsl = pharmaverseadam::adsl) { adsl |> dplyr::filter(SAFFL == "Y") |> dplyr::mutate(TRT01A = factor(TRT01A), SEX = factor(SEX)) } # 1. Direct table code: an rtables layout with a tern analysis function. demog_rtables <- function(adsl) { rtables::basic_table( title = "Demographics", subtitles = "Safety population" ) |> rtables::split_cols_by("TRT01A") |> rtables::add_overall_col("All patients") |> tern::analyze_vars( c("AGE", "SEX"), var_labels = c(AGE = "Age (years)", SEX = "Sex") ) |> rtables::build_table(adsl) } # 2. Direct table code: gtsummary. demog_gtsummary <- function(adsl) { gtsummary::tbl_summary( adsl, by = TRT01A, include = c(AGE, SEX), label = list(AGE = "Age (years)", SEX = "Sex") ) } # 3. ARD-first: compute the numbers as data, then render them. demog_ard <- function(adsl) { cards::ard_stack( adsl, .by = TRT01A, cards::ard_continuous(variables = AGE), cards::ard_categorical(variables = SEX), .attributes = TRUE # variable labels, for the rendered table ) } demog_from_ard <- function(ard) { gtsummary::tbl_ard_summary( ard, by = TRT01A, label = list(AGE = "Age (years)", SEX = "Sex") ) } # RTF output via gt. write_rtf <- function(tbl, path) { gt::gtsave(gtsummary::as_gt(tbl), path) invisible(path) } # Run only when called as a script (not when sourced by the tests). if (sys.nframe() == 0L) { adsl <- safety_adsl() print(demog_rtables(adsl)) print(gtsummary::as_kable(demog_gtsummary(adsl))) ard <- demog_ard(adsl) print(ard[ard$stat_name == "mean", c("group1_level", "variable", "stat")]) print(gtsummary::as_kable(demog_from_ard(ard))) path <- write_rtf(demog_gtsummary(adsl), file.path(tempdir(), "demog.rtf")) message("RTF written to ", path) }