From scripts to a package
Why package your R code, and how load_all() changes interactive development
The problem: source("helpers.R")
Most R developers begin building shared tools by creating a script. You write a handful of utility functions, save them to helpers.R or utils.R, and add a line to every analysis program:
helpers <- tempfile(fileext = ".R")
writeLines(
c(
"format_mean_sd <- function(x) sprintf('%.1f (%.1f)', mean(x), stats::sd(x))",
"summarise_ages <- function(age) paste0('n = ', length(age), ', ', format_mean_sd(age))"
),
helpers
)
source(helpers)
summarise_ages(c(64, 71, 80))
#> [1] "n = 3, 71.7 (8.0)"At first, this feels lightweight. But as an analysis codebase grows across programs and studies, three distinct problems emerge:
- Session pollution:
source()evaluates everything directly into the global environment (.GlobalEnv). Utility functions sit side by side with trial datasets, filtering flags, and temporary variables. If a helper script creates intermediate objects or masks an existing name, it alters the user’s active session silently. - Ghost functions: If you delete or rename a helper in
helpers.Rand re-source the file, the old function does not disappear from memory:
# Later you delete the helper from the file and source it again.
writeLines("summarise_ages <- function(age) paste0('n = ', length(age))", helpers)
source(helpers)
exists("format_mean_sd") # still there, from the old file
#> [1] TRUE
rm(format_mean_sd, summarise_ages, helpers) # clear this source() demonstrationBefore the rm() call, the deleted function remained in .GlobalEnv. Without removing it or restarting R, code could keep calling that stale helper; a fresh session would no longer have it.
- No package contract or metadata: A script provides no formal declaration of what packages it requires, no version number, no integrated documentation, and no standard test harness. When different analysts copy
helpers.Rinto their own project directories, the copies drift.
Moving helpers into a package gives their code, metadata, documentation, and tests a common structure. devtools::load_all() keeps newly loaded package functions out of .GlobalEnv; clear any bindings left by earlier source() calls separately.
The web-repo way: manifests, layouts, and editable installs
JavaScript and Python projects often organise reusable code into packages with project manifests.
In Node, package.json declares the package name, semantic version, and runtime dependencies:
{
"name": "agesum",
"version": "0.1.0",
"main": "src/index.js",
"dependencies": {
"lodash": "^4.17.21"
},
"devDependencies": {
"vitest": "^1.6.0"
}
}In Python, pyproject.toml standardises build specifications and metadata:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "agesum"
version = "0.1.0"
dependencies = [
"polars>=0.20.0"
]Both ecosystems commonly keep source code and tests in structured directories. For Python, an editable install (pip install -e .) makes development files importable without copying them; ordinary source edits do not require reinstalling the project. An already running Python session may need to reload a module, and metadata or compiled-code changes may need another install or build.
The R package structure maps directly to these concepts:
| Concept | Node / JavaScript (package.json) |
Python (pyproject.toml) |
R package |
|---|---|---|---|
| Manifest & metadata | package.json |
pyproject.toml ([project]) |
DESCRIPTION |
| Source code layout | src/ |
src/<pkg>/ |
R/ |
| Exported interface | exports / main field |
Names re-exported in __init__.py |
NAMESPACE (export() lines) |
| Automated test suite | test/ (Vitest, Jest) |
tests/ (pytest) |
tests/testthat/ |
| Excluded build assets | files field / .npmignore |
Build backend exclusion rules | .Rbuildignore |
| In-session dev workflow | npm link / workspaces |
pip install -e . (editable install) |
devtools::load_all() |
The R way: anatomy, creation, and the load_all() loop
An R package is a directory structured according to R’s conventions. DESCRIPTION and NAMESPACE are required; a package with R functions also has an R/ directory. The other directories below serve particular purposes and may be absent:
DESCRIPTION: The project manifest. It defines the package name, title, version, author details, license, and external package dependencies (ImportsandSuggests).NAMESPACE: Declares which functions are exported to callers and which functions are imported from other packages. Although it resembles R code, R parses it as an export/import specification rather than executing it.R/: Contains R code files defining functions. Files inR/should only assign objects; they should not run analysis scripts or attach libraries.man/: Help documentation files in Rd format. You rarely write Rd files manually; roxygen2 generates them from code comments (covered in a later post).tests/testthat/: Contains automated unit tests alongside the test runner scripttests/testthat.R(see testthat essentials)..Rbuildignore: Lists Perl-compatible regular expressions (one per line) matching files and folders to exclude when building a package bundle.
After create_package(), use_r("ages") and use_testthat(3) (all shown below), the tree is small:
agesum/
├── DESCRIPTION
├── NAMESPACE
├── R/
│ └── ages.R
└── tests/
├── testthat/
└── testthat.R
Creating the package skeleton
The {usethis} package creates this skeleton in one step. Run this command outside of any existing R project or repository:
usethis::create_package("~/code/agesum")usethis::create_package() writes DESCRIPTION, NAMESPACE, and an empty R/ directory. Its rstudio argument defaults to rstudioapi::isAvailable(), which is TRUE inside RStudio; then it also writes <pkg>.Rproj, .gitignore, and .Rbuildignore.
The generated DESCRIPTION file provides the standard package metadata template:
Package: agesum
Title: What the Package Does (One Line, Title Case)
Version: 0.0.0.9000
Authors@R:
person("First", "Last", , "first.last@example.com", role = c("aut", "cre"))
Description: What the package does (one paragraph).
License: `use_mit_license()`, `use_gpl3_license()` or friends to pick a
license
Config/roxygen2/version: 8.1.0
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
Several details in this file are worth noting:
Version: 0.0.0.9000is usethis’s default development version; update it as you release the package.Config/roxygen2/version: 8.1.0records the roxygen2 version used to generate documentation (which replaced the olderRoxygenNotefield starting in roxygen2 8.0.0).- The
Licenseline is a placeholder. You can set an appropriate open-source or proprietary license using helpers such asusethis::use_mit_license()orusethis::use_proprietary_license()(see repo hygiene files).
To add code and testing directories to your new package, run:
usethis::use_r("ages") # creates R/ages.R
usethis::use_testthat(3) # creates tests/testthat/ and tests/testthat.RInside R/ages.R, define your functions:
format_mean_sd <- function(x) {
sprintf("%.1f (%.1f)", mean(x), stats::sd(x))
}
summarise_ages <- function(age) {
paste0("n = ", length(age), ", mean (SD) = ", format_mean_sd(age))
}The new NAMESPACE has no exports yet. devtools::load_all() makes these functions callable during development, but an installed user cannot call summarise_ages() through agesum:: until it is exported; a later post covers that step.
Format and lint your package files with Air and lintr just like any other R project (see hooks, formatting, and linting).
The devtools::load_all() loop
In a script-based workflow, developers rely on source() to pull updated functions into memory. In package development, the core workflow engine is devtools::load_all() (in RStudio, Cmd+Shift+L on macOS or Ctrl+Shift+L on Windows and Linux; Positron has a “load package” shortcut too).
devtools::load_all() # Cmd/Ctrl + Shift + L
#> ℹ Loading agesum
summarise_ages(c(64, 71, 80))
#> [1] "n = 3, mean (SD) = 71.7 (8.0)"
format_mean_sd(c(64, 71, 80)) # internal helper: visible during development
#> [1] "71.7 (8.0)"Under the hood, devtools::load_all() calls pkgload::load_all(). It approximates building, installing, and attaching the package, without installing anything. It provides several advantages over sourcing:
- Clean namespace separation: Sourced scripts put functions into
.GlobalEnv. In contrast,load_all()loads them into the package namespace and attachespackage:agesumto R’s search path. These package functions do not create new.GlobalEnvbindings. - Access to internal functions: By default (
export_all = TRUE),load_all()makes unexported helpers available in your interactive console. You can inspect and test internal algorithms directly without adding temporary export declarations. - Cleanup within the package: Re-running
devtools::load_all()after deleting or renaming a function inR/removes it from the reloaded package environment. It does not remove an old function left in.GlobalEnvby an earliersource(); remove that binding or restart R. - Dependency handling: External packages declared in
DESCRIPTIONImportsare loaded into memory so that internal package calls succeed, without attaching them to the search path. - Test helper availability: If your package uses
{testthat}, files matchingtests/testthat/helper-*.Rare loaded into memory automatically duringload_all().
When top-level code in R/ runs
When transitioning from scripts to packages, the most critical adjustment is understanding when code executes.
In a script, top-level expressions execute sequentially every time the file is sourced:
# Acceptable in a one-off script, but WRONG inside a package R/ file:
library(dplyr)
study_data <- read.csv("data/raw.csv")
run_date <- Sys.Date()For an installed package, top-level expressions in R/ are evaluated when the package binary is created (often while installing from source). library() later loads the saved objects; it does not re-run those expressions. During development, devtools::load_all() re-sources R/ files on each load. A top-level run_date <- Sys.Date() can therefore change during development but remain fixed at the package binary’s build date for installed users.
Likewise, avoid calling library() or source() at the top level of an R/ file:
- Dependencies belong in
DESCRIPTION(Imports), referenced in code viapkg::fun()or imported viaNAMESPACE. - File loading belongs in package data workflows (
data/orinst/extdata/), not top-levelread.csv()calls. - Files in
R/should do exactly one thing: define and assign functions and objects.
When to use a script vs a package
A practical rule of thumb is to keep a study-specific analysis in its project and package functions that several analyses will reuse:
- Use analysis projects and scripts for study-specific deliverables: deriving study ADaM datasets, generating numbered clinical study report tables, figures, and listings (TFLs), or running exploratory analyses. These workflows have specific data inputs and fixed outputs, best managed in project directories using tools like renv, targets, or Quarto.
- Use a package for logic that will be reused across studies, projects, or team members: standardised statistical algorithms, company-wide table formatting helpers, custom plotting themes, and shared validation utilities.
The GxP angle: a place to collect evidence
A package gives code, version metadata, documentation, and tests predictable locations. In regulated work, that can make it easier to collect evidence for a risk assessment, but the structure alone does not establish that the code is suitable for its intended use.
The R Validation Hub white paper considers a package’s purpose, maintenance practices, community usage, and testing. Teams still need to assess those criteria for their intended use, run and review appropriate tests, and keep the results. See validation-ready R packages.
Looking ahead
Turning scripts into a minimal package is the first step toward robust R engineering. The subsequent posts in this series expand each piece of the package workflow:
- Post 2 covers the package development cycle and running
R CMD check. - Post 3 examines managing dependencies and importing functions in
NAMESPACE. - Post 4 details writing function documentation and roxygen2 tags.
Companion code
View first-package-demo.R · Download
Builds a throwaway package in a temporary directory, writes a function and helper into R/, loads them with pkgload::load_all(), and shows how reloading drops the deleted helper. The function is available during development; exporting it for installed users is covered later. Requires {usethis}, {pkgload}, {withr}, and {testthat}.
first-package-demo.R
# 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
}Sources
Standards & R manuals
- Writing R Extensions (§1.1 Package structure, §1.1.5, §1.3.2, §1.5): cran.r-project.org/doc/manuals/r-release/R-exts.html
- R Validation Hub: A Risk-based Approach for Assessing R package Accuracy within a Validated Infrastructure — pharmar.org/white-paper
R package development guide
- R Packages (2e), Introduction: r-pkgs.org/introduction.html
- R Packages (2e), The whole game: r-pkgs.org/whole-game.html
- R Packages (2e), Package structure and state: r-pkgs.org/structure.html
- R Packages (2e), Fundamental development workflows: r-pkgs.org/workflow101.html
- R Packages (2e), R code: r-pkgs.org/code.html
- R Packages (2e), Package lifecycle: r-pkgs.org/lifecycle.html
Package documentation
- usethis: usethis.r-lib.org · CRAN page
- pkgload: pkgload.r-lib.org · CRAN page
- devtools: devtools.r-lib.org · CRAN page
- roxygen2: roxygen2.r-lib.org · CRAN page
- testthat: testthat.r-lib.org · CRAN page
- withr: withr.r-lib.org · CRAN page
- desc: desc.r-lib.org · CRAN page
Web-repo specifications
- Python Packaging User Guide (pyproject.toml): packaging.python.org/en/latest/guides/writing-pyproject-toml
- Python Packaging User Guide (src layout): packaging.python.org/en/latest/discussions/src-layout-vs-flat-layout
- pip local project installs (editable mode): pip.pypa.io/en/stable/topics/local-project-installs
- npm package.json documentation: docs.npmjs.com/cli/configuring-npm/package-json
- npm link and workspaces: npm link · workspaces
- Positron R keyboard shortcuts: Positron R guide