R
R packages
Best practices
R package development series · part 2

The package development loop and R CMD check

From load_all() to check(): reading diagnostics and fixing common problems

Use the R package development loop, read R CMD check diagnostics, and fix four recurring problems.
Published

2026-09-29

The problem: check output as a wall of noise

R CMD check prints a long list of * checking ... lines, sometimes followed by diagnostics. A NOTE does not necessarily mean a package is broken, but dismissing diagnostics because code works in your console can hide a real problem. The check inspects package structure, metadata, code, documentation, examples, and tests. devtools::check() first builds a source tarball, then checks it in an independent R process.

The web-repo way: fast inner loops and pre-merge gates

Python and Node projects use lint, test, and build commands locally. CI can repeat them on a fresh runner and check a built artifact. Branch protection makes a passing CI job a merge requirement. R packages have a local loop (load_all(), document(), and test()) and a built-package check.

The R way: the loop, the check, and four common diagnostics

The inner loop: load, document, test, check

Four {devtools} commands form the development loop:

Step (RStudio shortcut) Calls What it does, and when
Load (Cmd/Ctrl+Shift+L) pkgload::load_all() Loads the source into a package-like namespace without installing, internal functions included. Run it after every edit in R/.
Document (Cmd/Ctrl+Shift+D) roxygen2::roxygenise() Rewrites man/*.Rd and NAMESPACE from roxygen comments. Run it after changing roxygen tags, exports or imports.
Test (Cmd/Ctrl+Shift+T) testthat::test_local() Runs tests/testthat/ against your current source. Run it after changing behaviour or tests.
Check (Cmd/Ctrl+Shift+E) pkgbuild::build(), then rcmdcheck::rcmdcheck() Builds the .tar.gz and runs the full R CMD check in a fresh R process. Run it before a pull request, a release or a merge.

Unlike devtools::test(), devtools::check() builds a .tar.gz archive with pkgbuild::build(), then passes it to rcmdcheck::rcmdcheck() in an independent R process. Your interactive workspace cannot affect the check. The archive excludes files listed in .Rbuildignore.

ImportantAlways document before checking

In older workflows, developers assumed devtools::check() automatically re-documented their package. Under modern versions of {roxygen2} and {usethis}, new packages record Config/roxygen2/version in DESCRIPTION rather than the older RoxygenNote field. If RoxygenNote is absent, devtools::check() skips documentation generation silently.

To ensure your NAMESPACE and man/ files match your latest code before the build tarball is created, run devtools::document() explicitly, or pass document = TRUE:

devtools::document()
devtools::check()
# Or in a single invocation:
devtools::check(document = TRUE)

Notice also that devtools::check() is not identical to calling the command-line R CMD check directly. By default, devtools::check() configures sensible development defaults: it turns on --as-cran, adds --no-manual (bypassing the requirement for LaTeX to build a PDF manual), includes --timings, sets the environment variable NOT_CRAN = "true" so that testthat tests using skip_on_cran() run locally, and turns off incoming CRAN feasibility checks.

What R CMD check actually does

Section 1.3.1 of Writing R Extensions specifies the responsibilities of R CMD check. When executed against a package tarball, the check runner performs a comprehensive inspection:

  • Unpacks and checks structure: It validates directory names, file permissions, and confirms that all top-level files conform to the standard R package specification.
  • Inspects metadata: It parses DESCRIPTION to verify required fields, licenses, valid R package version syntax, and package dependency syntax.
  • Installs into a private library: It creates a dedicated <package>.Rcheck/ directory at the check output location and installs the package there, separate from your usual library.
  • Checks R code: It checks syntax, then uses {codetools} to report possible problems such as undefined functions and variables.
  • Verifies documentation: It compares Rd files in man/ against the code, ensuring all exported functions have documentation and that listed argument names match the actual function signatures.
  • Executes examples: It runs eligible documentation examples (excluding \dontrun{} code), with C collation and LANGUAGE=en; an example failure is reported as an ERROR.
  • Executes the test suite: It runs all test files in tests/ in that isolated installation. A failing test expectation or uncaught error produces a check ERROR.
  • Rebuilds vignettes: It renders all vignettes in vignettes/ from source, ensuring reproducible execution.

The companion’s one-function package produced 39 * checking lines on this machine; other packages and check settings differ.

Reading the log: ERROR vs WARNING vs NOTE

As Hadley Wickham and Jenny Bryan summarise in R Packages (2e), check results fall into three explicit tiers:

  • ERROR: Severe problems that you must fix regardless of whether you submit to CRAN or share code internally. Examples include syntax errors, failing tests, unexecutable examples, or missing package dependencies. An ERROR causes the check command to exit with a nonzero status.
  • WARNING: Likely problems that must be resolved for public distribution and should rarely be accepted internally. Examples include undeclared package imports (pkg::fun() without declaring pkg in DESCRIPTION), non-ASCII characters in R source files, or documented arguments that do not exist in code. Warnings leave an exit status of 0, but the standard GitHub Action for R packages fails on them by default (see the CI section below).
  • NOTE: Mild issues or informational observations. Examples include variables flagged by codetools during data masking, declared dependencies that are never referenced, or non-standard files at the package root. A NOTE leaves an exit status of 0.

CRAN policy asks for checks without warnings or significant notes; it allows an explanation for notes that cannot be eliminated. For internal packages, investigate each new diagnostic and record why any remaining NOTE is acceptable.

Four recurring diagnostics and how to respond

The following examples show the reported message and a practical fix.

1. Global variable bindings in data masking (NOTE)

When writing data transformation functions with packages like {dplyr}, developers write column names directly:

# R/adults.R
#' Filter for adult subjects
#'
#' @param data A data frame containing an AGE column.
#' @return A filtered data frame.
#' @export
adults <- function(data) {
  dplyr::filter(data, AGE >= 18)
}

Running devtools::check() on this code produces a diagnostic NOTE:

* checking R code for possible problems ... NOTE
adults: no visible binding for global variable ‘AGE’
Undefined global functions or variables:
  AGE

codetools inspects R code using standard lexical scoping rules. Because AGE is neither passed as an argument to adults() nor defined locally inside the function, the checker flags it as a potentially missing global object.

The modern tidyverse solution is to use the .data pronoun from {rlang}, and import .data in your documentation tags:

# R/adults.R
#' Filter for adult subjects
#'
#' @param data A data frame containing an AGE column.
#' @return A filtered data frame.
#' @importFrom rlang .data
#' @export
adults <- function(data) {
  dplyr::filter(data, .data$AGE >= 18)
}

Two parts are required: using .data$AGE tells filter() to look inside the data frame, and #' @importFrom rlang .data tells R where the pronoun comes from (with rlang declared in DESCRIPTION Imports). If you use .data$AGE without importing .data, you trade one NOTE for another: no visible binding for global variable ‘.data’.

NoteData masking vs tidy selection

The .data pronoun applies to data-masking verbs (filter(), mutate(), summarise()). In tidy-selection verbs (select(), relocate()), the use of .data$col was deprecated in tidyselect 1.2.0 and produces a deprecation warning.

For tidy selection, pass column names as character strings (dplyr::select(data, "AGE")) or use tidyselect helpers (dplyr::select(data, dplyr::all_of(cols))).

An alternative approach is to declare global variables using utils::globalVariables() in a file such as R/globals.R:

# R/globals.R
utils::globalVariables("AGE")

While utils::globalVariables() silences the NOTE, be aware of the trade-off: it registers the name package-wide. If you accidentally register a misspelled name elsewhere, codetools will no longer flag that name as a possible missing variable. .data limits the change to the data-masking expression.

2. Undeclared dependencies (WARNING)

If you use a helper from an external package via :: without declaring that package in DESCRIPTION:

* checking dependencies in R code ... WARNING
'::' or ':::' import not declared from: ‘stringr’

Packages called with :: or ::: must be declared in DESCRIPTION. Use Imports for a dependency required at runtime; an optional dependency can go in Suggests when the call is guarded. For this required stringr example, run usethis::use_package("stringr"). A declared import that is never used may produce Namespace in Imports field not imported from: ‘stringr’.

3. Non-ASCII characters in R source code (WARNING)

If you write mathematical symbols or special characters directly in an R string literal:

* checking code files for non-ASCII characters ... WARNING
Found the following file with non-ASCII characters:
  R/adults.R
Portable packages must use only ASCII characters in their R code [...]
Use \uxxxx escapes for other characters.

Non-ASCII bytes in R source files trigger a WARNING because files encoded on one operating system or locale may fail to parse or compile on another.

The fix is to write the string using standard Unicode escape sequences (\uxxxx):

label <- "\u2265 18 years"
label

The source file contains only portable 7-bit ASCII characters, while R renders the intended symbol at runtime. You can inspect any file for non-ASCII bytes using tools::showNonASCIIfile("R/adults.R").

4. Non-standard top-level files (NOTE)

If you leave ad-hoc files at the root of your package repository (such as notes.txt or exploratory scripts):

* checking top-level files ... NOTE
Non-standard file/directory found at top level:
  ‘notes.txt’

Because R packages have an explicit root layout (R/, man/, vignettes/, tests/, inst/, data/), unrecognised root files get bundled into the package tarball unless explicitly ignored. Note that this check is enabled under --as-cran (the default in devtools::check()).

To exclude a file from the build artifact, register it in .Rbuildignore using usethis::use_build_ignore("notes.txt"). This adds the regular expression ^notes\.txt$ to .Rbuildignore. Lines in .Rbuildignore are evaluated as Perl-compatible regular expressions, matched case-insensitively against relative file paths during pkgbuild::build().

A result you can assert on: rcmdcheck()

While devtools::check() is designed for interactive console output, {rcmdcheck} provides a programmable interface. When writing automated scripts, custom build validation tools, or smoke tests, use rcmdcheck::rcmdcheck():

result <- rcmdcheck::rcmdcheck(
  path = ".",
  args = c("--no-manual", "--as-cran"),
  error_on = "never",
  quiet = TRUE,
  env = c(NOT_CRAN = "true")
)

# Inspect counts and diagnostics
result$status # 0 if clean or warnings/notes only; nonzero on error
result$notes  # character vector of NOTE messages
length(result$warnings)

When running your own check outside CRAN, set NOT_CRAN=true if you need skip_on_cran() tests to execute; rcmdcheck() does not set it for you.

rcmdcheck() returns a result object with status, errors, warnings, notes, and checkdir. Inspect the diagnostic vectors directly. The default check folder is temporary and is removed after the result object is discarded; pass check_dir = "check" to retain its logs.

error_on controls when rcmdcheck() raises an R error: "never", "error", "warning", or "note". The check completes first unless it times out.

The pre-merge gate in CI

When configured for pull requests, CI can run the check on each one. The GitHub Action r-lib/actions/check-r-package runs rcmdcheck::rcmdcheck() on a fresh runner with these defaults:

args: 'c("--no-manual", "--as-cran")'
error-on: '"warning"'

A WARNING fails that job; a required status check then blocks merging until it passes. For setup details, dependency caching, and matrix configurations, see CI with GitHub Actions.

Companion code

View check-demo.R · Download

Builds a throwaway package in a temporary directory, triggers a no visible binding for global variable check NOTE, inspects it with rcmdcheck::rcmdcheck(), applies the .data fix, and re-checks clean. Requires {devtools}, {rcmdcheck}, {usethis}, {withr}, {dplyr}, and {rlang}.

# The package development loop and R CMD check: builds a throwaway package in a
# temporary folder, writes a function with an undeclared column name that triggers
# a check NOTE, runs rcmdcheck::rcmdcheck() to inspect the issue, applies the
# .data fix, and re-runs the check clean.
#
#   Rscript check-demo.R

planted_column <- "AGE"

adults_code <- function(fixed = FALSE) {
  if (fixed) {
    c(
      "#' Filter for adult subjects",
      "#'",
      "#' @param data A data frame containing an AGE column.",
      "#' @return A filtered data frame.",
      "#' @importFrom rlang .data",
      "#' @export",
      "adults <- function(data) {",
      "  dplyr::filter(data, .data$AGE >= 18)",
      "}"
    )
  } else {
    c(
      "#' Filter for adult subjects",
      "#'",
      "#' @param data A data frame containing an AGE column.",
      "#' @return A filtered data frame.",
      "#' @export",
      "adults <- function(data) {",
      "  dplyr::filter(data, AGE >= 18)",
      "}"
    )
  }
}

make_demo_package <- function(path = file.path(tempdir(), "checkdemo")) {
  withr::local_options(usethis.quiet = TRUE)
  usethis::create_package(
    path,
    fields = list(
      Title = "Demo Package for R CMD Check",
      Description = "Filters subject-level data; used to show a check NOTE."
    ),
    rstudio = FALSE,
    open = FALSE
  )
  usethis::with_project(path, {
    usethis::use_mit_license("Demo authors")
    usethis::use_package("dplyr")
  })
  writeLines(adults_code(fixed = FALSE), file.path(path, "R", "adults.R"))
  devtools::document(path, quiet = TRUE)
  invisible(path)
}

fix_package <- function(path) {
  withr::local_options(usethis.quiet = TRUE)
  usethis::with_project(path, {
    usethis::use_package("rlang")
  })
  writeLines(adults_code(fixed = TRUE), file.path(path, "R", "adults.R"))
  devtools::document(path, quiet = TRUE)
  invisible(path)
}

run_check <- function(path, quiet = TRUE) {
  rcmdcheck::rcmdcheck(
    path,
    args = "--no-manual",
    quiet = quiet,
    error_on = "never"
  )
}

check_counts <- function(result) {
  c(
    errors = length(result$errors),
    warnings = length(result$warnings),
    notes = length(result$notes)
  )
}

if (sys.nframe() == 0L) {
  demo_dir <- file.path(tempdir(), "checkdemo")
  if (dir.exists(demo_dir)) {
    unlink(demo_dir, recursive = TRUE)
  }
  pkg_path <- make_demo_package(demo_dir)
  message("Running initial check (expecting 1 NOTE)...")
  res1 <- run_check(pkg_path, quiet = TRUE)
  print(check_counts(res1))
  cat("\nCheck output:\n", res1$notes, "\n\n", sep = "")

  message("Applying .data fix and re-checking...")
  fix_package(pkg_path)
  res2 <- run_check(pkg_path, quiet = TRUE)
  print(check_counts(res2))
  unlink(demo_dir, recursive = TRUE)
}

Sources

Standards & R manuals

R package development guide

Package documentation

CI actions