# From scripts to a package: builds a throwaway package in a temporary folder, # writes one function and one helper into R/, loads the # package with pkgload::load_all() and calls the function. Then it edits the # file and loads again, to show that load_all() replaces the old code (unlike # source(), which leaves deleted functions behind in your workspace). # # Rscript first-package-demo.R # The code a script writer would have kept in a sourced helpers file. ages_code <- c( "# Internal helper: not exported, but visible after load_all().", "format_mean_sd <- function(x) {", " sprintf(\"%.1f (%.1f)\", mean(x), stats::sd(x))", "}", "", "#' Summarise ages as n and mean (SD)", "summarise_ages <- function(age) {", " paste0(\"n = \", length(age), \", mean (SD) = \", format_mean_sd(age))", "}" ) # The same file after an edit: the helper is gone. ages_code_edited <- c( "#' Summarise ages as n", "summarise_ages <- function(age) {", " paste0(\"n = \", length(age))", "}" ) # Creates the package at `path` (the folder name is the package name) and # returns its path. create_demo_package <- function(path) { withr::local_options(usethis.quiet = TRUE) usethis::create_package(path, rstudio = FALSE, open = FALSE) usethis::with_project(path, { usethis::use_testthat(3) }) writeLines(ages_code, file.path(path, "R", "ages.R")) invisible(path) } # Every file in the package, relative to its root. package_files <- function(path) { sort(list.files(path, recursive = TRUE, all.files = TRUE)) } # Loads the package from source and returns its namespace. load_demo_package <- function(path) { pkgload::load_all(path, quiet = TRUE)$env } edit_demo_package <- function(path) { writeLines(ages_code_edited, file.path(path, "R", "ages.R")) } # Run only when called as a script (not when sourced by the tests). if (sys.nframe() == 0L) { path <- file.path(tempdir(), "agesdemo") create_demo_package(path) print(package_files(path)) load_demo_package(path) ages <- c(64, 71, 80) print(summarise_ages(ages)) print(format_mean_sd(ages)) # internal, yet callable after load_all() edit_demo_package(path) load_demo_package(path) print(summarise_ages(ages)) print(exists("format_mean_sd")) # FALSE: the deleted helper is gone }