Enterprise R - Packages, Testing and Environments

Article · 3:00

Turning scripts into a package, testing it with testthat, locking the environment with renv, and running it without a human.

The step from analysis to software is smaller in R than people expect, and a package is the unit it happens in. A package is not only for CRAN - most are internal, and the reason to build one is that it gives you a standard place for functions, documentation, tests and dependencies, and a single install that gets a colleague all of it.

usethis and devtools do the work. create_package() lays out the skeleton, use_r("name") makes a source file, and load_all() (Ctrl+Shift+L) reloads everything without installing - that is the loop you will live in. Functions go in R/, and DESCRIPTION lists dependencies under Imports.

Documentation comes from roxygen2 comments starting #' directly above each function. @param documents an argument, @return the result, @examples gives runnable examples that are checked by R CMD check, and @export makes a function public. document() turns these into the .Rd help files and the NAMESPACE. Keeping documentation in the same file as the code is what stops it drifting from reality.

Testing is testthat. use_testthat() sets it up, use_test("name") creates a test file, and a test is test_that("description", { expect_equal(...) }). The expectations you will use most are expect_equal, expect_error, expect_warning, expect_true and expect_snapshot for output that is awkward to assert on precisely.

The habit worth forming: when you find a bug, write the failing test first and watch it fail. Then fix it. That way you know the test detects the bug, rather than hoping it would have, and it stays in the suite to stop the bug returning.

renv solves the problem that your analysis depends on the versions of forty packages and install.packages() always gives the newest. renv::init() creates a project-local library and a lockfile recording the exact version of everything. Commit renv.lock; a colleague runs renv::restore() and gets the same versions you had. Without it, "it worked last year" is a statement about a library that no longer exists.

Automation: Rscript analysis.R runs a script from the command line, commandArgs() reads its arguments, and cron or Task Scheduler runs it on a schedule. Log what it did and make it fail loudly - a scheduled job that errors quietly is worse than no job, because it looks like it ran.

# ---- Creating a package ----------------------------------------------
# usethis::create_package("~/code/salesreport")
# usethis::use_mit_license("Your Name")
# usethis::use_git()
# usethis::use_r("summarise_sales")     # creates R/summarise_sales.R

# ---- R/summarise_sales.R, with roxygen2 documentation ---------------

#' Summarise sales by region
#'
#' Totals revenue and counts orders for each region, dropping rows whose
#' revenue is missing and reporting how many were dropped.
#'
#' @param data A data frame with `region` and `revenue` columns.
#' @param min_orders Integer. Regions with fewer orders are excluded.
#'   Defaults to 1.
#'
#' @return A tibble with one row per region and columns `region`,
#'   `orders` and `revenue`, sorted by revenue descending.
#'
#' @examples
#' sales <- data.frame(region = c("n", "s", "n"), revenue = c(10, 20, 5))
#' summarise_sales(sales)
#'
#' @export
summarise_sales <- function(data, min_orders = 1) {
  stopifnot(
    is.data.frame(data),
    all(c("region", "revenue") %in% names(data)),
    is.numeric(min_orders), length(min_orders) == 1
  )

  dropped <- sum(is.na(data$revenue))
  if (dropped > 0) {
    warning(dropped, " rows had a missing revenue and were dropped")
  }

  data |>
    dplyr::filter(!is.na(.data$revenue)) |>
    dplyr::summarise(
      orders  = dplyr::n(),
      revenue = sum(.data$revenue),
      .by     = "region"
    ) |>
    dplyr::filter(.data$orders >= min_orders) |>
    dplyr::arrange(dplyr::desc(.data$revenue))
}

# dplyr:: rather than library(dplyr) inside a package, and .data$ for
# column names - both are what R CMD check expects, and the second
# stops "no visible binding for global variable" notes.

# ---- The development loop --------------------------------------------
# devtools::load_all()     Ctrl+Shift+L - reload without installing
# devtools::document()     roxygen comments -> help files + NAMESPACE
# devtools::test()         run the tests
# devtools::check()        everything CRAN would check. Run it often.

# ---- tests/testthat/test-summarise_sales.R --------------------------
# usethis::use_testthat(); usethis::use_test("summarise_sales")

test_that("it totals revenue per region", {
  sales <- data.frame(region = c("n", "s", "n"), revenue = c(10, 20, 5))
  out   <- summarise_sales(sales)

  expect_equal(nrow(out), 2)
  expect_equal(out$revenue[out$region == "n"], 15)
  expect_s3_class(out, "data.frame")
})

test_that("it rejects a frame without the columns it needs", {
  expect_error(summarise_sales(data.frame(x = 1)))
})

test_that("it warns rather than silently dropping missing revenue", {
  sales <- data.frame(region = c("n", "n"), revenue = c(10, NA))
  expect_warning(summarise_sales(sales), "missing revenue")
})

test_that("min_orders filters small regions", {
  sales <- data.frame(region = c("n", "n", "s"), revenue = c(1, 2, 3))
  expect_equal(nrow(summarise_sales(sales, min_orders = 2)), 1)
})

# ---- renv: lock the versions ----------------------------------------
# renv::init()         a project library + renv.lock. Commit the lock.
# renv::snapshot()     record what is installed now
# renv::restore()      install exactly what the lock says
# renv::status()       what has drifted since the snapshot
#
# Without this, "it worked last year" describes a library that no
# longer exists anywhere.

# ---- Running it without a human -------------------------------------
# Rscript analysis.R --date 2026-11-23
#
#   args <- commandArgs(trailingOnly = TRUE)
#
# cron, nightly at 02:00:
#   0 2 * * * cd /srv/reports && /usr/bin/Rscript analysis.R >> run.log 2>&1
#
# Make it fail LOUDLY. A scheduled job that errors quietly looks exactly
# like one that ran:
#   options(error = function() { quit(status = 1) })

Where to go from here

Longer reading about this subject, written alongside the course.

Course guide How to work through this course What each phase is for, the four things to build alongside it, the base R and tidyverse confusion explained once, and what to skip on a first pass. 4 min read
  • NA is contagious, and it is the best decision R ever made

    Every other language treats a missing value as an inconvenience to route around. R treats it as information, and makes it spread through every calculation it touches until you say, in writing, what you want done about it. That is not an annoyance. It is the feature that stops you publishing a wrong number.

    · 9 min read

Discussion

No questions on this topic yet. Sign in to ask the first one.