Dependencies: DESCRIPTION and NAMESPACE

How packages declare what they need, how NAMESPACE borrows functions, and why library() belongs only in scripts

Declare external packages in DESCRIPTION Imports and Suggests, call functions through pkg::fun() or @importFrom, and guard optional dependencies cleanly.
Published

2026-09-29

The problem: library() in package code

In an analysis script, a line such as library(dplyr) or library(tools) does two jobs simultaneously: it declares that the script expects a package to be installed, and it attaches that package’s exported functions directly onto the search path so you can call filter() or file_ext() unqualified.

When developers convert an analysis script into an R package, they often keep those library() calls at the top of files in R/:

# R/ext.R
library(tools)

get_ext <- function(path) {
  file_ext(path)
}

During interactive package development, this pattern appears to work. When you run pkgload::load_all(), the development helper sources the files in R/ into an interactive environment, which attaches {tools} to your current session search path. get_ext("trial_data.csv") returns "csv" without error.

Once the package is installed via R CMD INSTALL, however, top-level code in R/ behaves differently. Top-level statements run during package installation to prepare the namespace image. When a user later loads your package with library(mypkg) in a fresh session, those top-level lines do not re-run. The {tools} namespace is never attached to the user’s search path. Calling get_ext("trial_data.csv") immediately fails:

Error in file_ext(path) : could not find function "file_ext"

Placing library() inside a function body creates a different failure mode:

get_ext <- function(path) {
  library(tools)
  file_ext(path)
}

Inside a function, library() mutates the search path of whoever called it. Attaching a package as a side effect of calling a calculation or utility function can silently mask functions in the user’s workspace. R CMD check flags this practice explicitly with a WARNING:

* checking dependencies in R code ... WARNING
'library' or 'require' call not declared from: ‘tools’
'library' or 'require' call to ‘tools’ in package code.
  Please use :: or requireNamespace() instead.
  See section 'Suggested packages' in the 'Writing R Extensions' manual.

In our check run on R 4.6.1 (with {tools} declared in Imports), a top-level library(tools) escaped that 'library' or 'require' WARNING, but R CMD check still caught the breakdown with two NOTEs: Namespace in Imports field not imported from: 'tools' and get_ext: no visible global function definition for 'file_ext'.

A package cannot rely on script-style attachment. It must separate what must be installed from how individual functions are referenced.

The web-repo way: manifest declarations and explicit imports

Developers working in Node (package.json) or Python (pyproject.toml) will recognize this division immediately:

  • Runtime dependencies: Node lists production packages in dependencies; Python lists required distributions in dependencies under [project].
  • Development tools: Node uses devDependencies for local test and build tools.
  • Optional dependencies: npm’s optionalDependencies lets installation continue if one is unavailable. Python’s [project.optional-dependencies] defines extras a consumer can request, such as mypkg[report].
  • Local imports: Source files import names they use, for example import { readFile } from "node:fs/promises" and from os.path import splitext. Those names are bound in that module, unlike R’s package-wide NAMESPACE imports.

R adopts the same conceptual division, but implements it with two distinct files:

  1. DESCRIPTION acts as the package manifest. It tells package managers (install.packages(), pak) what external packages must be installed on the machine.
  2. NAMESPACE controls symbol visibility. It informs R’s namespace mechanism which external functions your package code borrows, and which internal functions your package exports to consumers.

The critical difference to keep in mind is that in R, NAMESPACE imports are package-wide, not file-scoped. A symbol imported in NAMESPACE is accessible to every function across all files in R/. Furthermore, listing a package under Imports: in DESCRIPTION does not actually import any functions into your code; it ensures installation and namespace availability, leaving the import mechanism to NAMESPACE or ::.

The R way: DESCRIPTION fields and NAMESPACE resolution

DESCRIPTION: choosing the correct dependency field

Section 1.1.3 of Writing R Extensions defines the four main dependency fields in DESCRIPTION:

Field When to use it Installed by default? Attached to search path?
Imports Required packages whose functions you call via pkg::fun() or @importFrom. Yes (by install.packages()) No
Suggests Packages used only in unit tests, vignettes, documentation examples, or optional helper functions. No No
Depends Minimum R version requirements (R (>= 4.1)), or rare meta-packages designed to expose another package’s entire API. Yes Yes
LinkingTo Packages providing C/C++ header files at compilation time (such as {cpp11} or {Rcpp}). Yes No

Don’t list a package in both Depends and Imports. LinkingTo is separate: a package such as {Rcpp} often appears in both Imports and LinkingTo.

Why Depends is rarely appropriate for packages

In early versions of R, Depends was the standard method for declaring dependencies. However, because Depends attaches the listed packages to the search path whenever your package is attached, it pollutes the user’s workspace with symbols they did not request. As Hadley Wickham and Jenny Bryan emphasize in R Packages (2e), you should list packages in Imports, not Depends. Writing R Extensions (§1.1.3) similarly notes: “Field ‘Depends’ should nowadays be used rarely”.

Reserve Depends almost exclusively for declaring the minimum R version required by your code:

Depends:
    R (>= 4.1)

Specifying minimum versions

If your code relies on a feature introduced in a recent release of a dependency, pin the minimum version in parentheses: cli (>= 3.6.0).

Depends:
    R (>= 4.1)
Imports:
    cli (>= 3.6.0),
    rlang
Suggests:
    knitr,
    testthat (>= 3.0.0)

In our tests on R 4.6.1, pkgload::load_all() and R CMD check both halt if an installed dependency fails to satisfy a declared minimum version requirement, reporting that an unsuitable version is present.

Automating declarations with {usethis}

Rather than editing DESCRIPTION manually, use usethis::use_package() to modify fields safely:

usethis::use_package("cli", min_version = "3.6.0")
usethis::use_package("knitr", type = "Suggests")
usethis::use_package("R", type = "Depends", min_version = "4.1")

When you add a dependency, {usethis} updates the correct field and reminds you how to call its functions:

✔ Adding cli to 'Imports' field in DESCRIPTION.
☐ Refer to functions with `cli::fun()`.
✔ Adding knitr to 'Suggests' field in DESCRIPTION.
☐ Use `requireNamespace("knitr", quietly = TRUE)` to test if knitr is installed.
☐ Then directly refer to functions with `knitr::fun()`.

If you specify min_version = TRUE, {usethis} reads the version currently installed in your library and sets that as the lower bound. If you request type = "Depends" for a package, {usethis} warns:

! Are you sure you want 'Depends'? 'Imports' is almost always the better choice.

If a package is already in Suggests, calling use_package("pkg", type = "Imports") promotes it. However, {usethis} will not demote an entry from Imports to Suggests, nor does it provide a helper function to remove dependencies; when you drop a dependency, delete the entry from DESCRIPTION by hand.

NAMESPACE: calling external functions

Once an external package is declared in DESCRIPTION, you have three ways to call its functions from R/:

1. The default: pkg::fun()

The recommended default in modern R package engineering is to call external functions explicitly with the double-colon operator: cli::cli_inform().

Calling pkg::fun() offers three distinct benefits: - Provenance: Anyone reading the code knows exactly where the function originates without searching through NAMESPACE or roxygen comments. - Conflict prevention: It eliminates name collisions between packages. - On-demand loading: When your package is loaded, packages referenced only via :: are loaded on first use rather than immediately at package load time. (By contrast, pkgload::load_all() loads all packages listed in Imports up front during development).

2. Selective imports: @importFrom

Infix operators are awkward to call with ::: rlang::`%||%`(x, y) works but is harder to read than x %||% y. For functions called repeatedly in a tight loop, an import can also avoid repeated namespace lookups.

To import specific functions into your package’s namespace, add the @importFrom roxygen tag above the calling function:

# R/summary.R

#' Format a summary label
#'
#' @param x A vector of values.
#' @param label An optional display label.
#' @return Invisible NULL; emits an informative message.
#' @importFrom rlang %||%
#' @export
summary_label <- function(x, label = NULL) {
  label <- label %||% "Summary"
  cli::cli_inform("{label}: {length(x)} value{?s}")
}

When you run devtools::document(), {roxygen2} writes the corresponding directive to NAMESPACE. In {roxygen2} 8.1.0, multiple @importFrom directives for the same external package are collapsed into a single multi-line statement:

export(summary_label)
importFrom(rlang,"%||%")

To keep import tags in one place, first create package-level documentation with usethis::use_package_doc() if your package has none. Then usethis::use_import_from("rlang", "%||%") places the tag in R/<pkg>-package.R and updates NAMESPACE.

3. Why to avoid full package imports: @import

The @import pkg tag instructs {roxygen2} to write import(pkg) into NAMESPACE, pulling all exported symbols from that package into your package’s namespace.

While this saves typing, it creates subtle bugs when two imported packages export overlapping names. For example, if a package uses both @import dplyr and @import stats, loading the package prints a collision warning:

replacing previous import ‘dplyr::filter’ by ‘stats::filter’ when loading ‘mypkg’

Inside this package, an unqualified filter() resolves to stats::filter(). Code that expected dplyr::filter() may then error or produce the wrong result. For this reason, R Packages (2e) recommends pkg::fun() or @importFrom for most code. Stick to pkg::fun() as your default, supplemented by targeted @importFrom tags.

Optional packages: the Suggests guard

Packages listed in Suggests are not installed by default when someone installs your package. If an optional calculation, report formatter, or export function requires a suggested package, you must verify its presence before invoking it.

R provides two distinct patterns for guarding optional dependencies.

Pattern 1: Asserting presence with rlang::check_installed()

When a function cannot proceed without the optional package, use rlang::check_installed(). It accepts a human-readable reason explaining why the package is needed:

markdown_table <- function(data) {
  rlang::check_installed("knitr", reason = "to format the table as Markdown")
  knitr::kable(data, format = "pipe")
}

markdown_table(head(mtcars[, 1:3], 3))

If the package is missing, rlang::check_installed() behaves according to session interactivity: - In an interactive session, it prompts the user with an option to install the missing package via pak or install.packages(). - In a non-interactive session (such as a batch calculation, CI runner, or automated reporting pipeline), it aborts evaluation immediately with an error of class rlib_error_package_not_found:

tryCatch(
  rlang::check_installed("notarealpkg", reason = "to format the table as Markdown"),
  error = function(e) class(e)
)

The error condition contains a $pkg element naming the missing dependency, and attributes the error to the calling function rather than the internal check. You can also specify minimum version constraints directly in the guard: rlang::check_installed("knitr (>= 1.40.0)").

Pattern 2: Graceful degradation with requireNamespace()

If your function can fall back to a base R method or alternative representation when the suggested package is unavailable, use requireNamespace(..., quietly = TRUE):

as_table <- function(data) {
  if (requireNamespace("knitr", quietly = TRUE)) {
    knitr::kable(data, format = "pipe")
  } else {
    data
  }
}

as_table(head(mtcars[, 1:2], 2))

The argument quietly = TRUE is essential. If omitted, R prints a diagnostic message to standard error whenever the package is absent:

Loading required namespace: notarealpkg
Failed with error:  ‘there is no package called ‘notarealpkg’’

Do not use require() for conditioning in package code. Unlike requireNamespace(), require() attempts to attach the package to the user’s search path, emitting warnings on failure and polluting the session on success. The check WARNING above points to the same fix: use :: or requireNamespace() (see Writing R Extensions, §1.1.3.1).

Handling suggested packages in test suites

Developer machines and CI runners usually install Suggests packages, so tests that use {testthat} itself need no guard. Writing R Extensions still asks for suggested packages to be used conditionally.

When a test exercises an optional integration or a heavy package that may not be present in every testing environment, guard the test block with testthat::skip_if_not_installed():

test_that("markdown formatting renders valid pipe table", {
  testthat::skip_if_not_installed("knitr", minimum_version = "1.40.0")
  tbl <- markdown_table(head(mtcars, 2))
  expect_s3_class(tbl, "knitr_kable")
})

This prevents the test suite from generating false check failures when running on environments configured without optional dependencies.

The pharma angle: dependency assessment and verification boundaries

In regulated clinical reporting (GxP), every package declared in your manifest carries an evaluation footprint. As explored in Runtime dependency vetting and Validation-ready R packages, organisations must justify the integrity and stability of the software tools used to produce submission tables, figures, and listings.

An Imports entry makes a dependency available wherever your package is installed. Record direct and transitive dependencies, then assess their role in the actual workflow. The R Validation Hub distinguishes packages used directly from supporting imports and recommends focusing accuracy verification on the former; an Imports entry alone does not require separate accuracy qualification of its entire dependency tree. A package in Suggests still needs consideration if a production workflow uses it. Choose Imports when core functionality needs the package and Suggests when the feature is optional, rather than treating the field as a validation decision.

Companion code

View dependencies-demo.R · Download

Writes a DESCRIPTION file in a temporary folder using {desc}, extracts and classifies dependencies into a structured table, flags common declaration mistakes, and demonstrates an rlang::check_installed() guard.

# Dependencies, read from DESCRIPTION: writes a small DESCRIPTION into a temp
# folder, lists its dependencies with their minimum versions, flags two
# common mistakes, and shows a guard for a package that is only suggested.
#
#   Rscript dependencies-demo.R

# Writes a DESCRIPTION with three dependency fields and returns its folder.
write_demo_description <- function(path = tempfile("demopkg")) {
  dir.create(path, showWarnings = FALSE)
  d <- desc::desc(
    text = c(
      "Package: demopkg",
      "Title: Demo Package",
      "Version: 0.1.0",
      "Description: Shows how a package declares its dependencies.",
      "License: MIT + file LICENSE"
    )
  )
  d$set_dep("R", "Depends", ">= 4.1")
  d$set_dep("cli", "Imports", ">= 3.6.0")
  d$set_dep("rlang", "Imports")
  d$set_dep("testthat", "Suggests", ">= 3.0.0")
  d$set_dep("knitr", "Suggests")
  d$write(file = file.path(path, "DESCRIPTION"))
  path
}

# One row per dependency: its field, whether default installation needs it
# (Depends, Imports, LinkingTo), and the minimum version, if any.
dependency_table <- function(path) {
  deps <- desc::desc_get_deps(path)
  data.frame(
    package = deps$package,
    field = deps$type,
    required = deps$type %in% c("Depends", "Imports", "LinkingTo"),
    min_version = ifelse(
      deps$version == "*",
      NA_character_,
      sub("^>=\\s*", "", deps$version)
    )
  )
}

# Two rules from Writing R Extensions: a package belongs in only one field,
# and Depends is for R itself and (rarely) packages users need attached.
dependency_problems <- function(path) {
  deps <- desc::desc_get_deps(path)
  counts <- table(deps$package)
  c(
    sprintf("%s is listed in more than one field", names(counts)[counts > 1]),
    sprintf(
      "%s is in Depends: prefer Imports",
      setdiff(deps$package[deps$type == "Depends"], "R")
    )
  )
}

# The guard for a suggested package: stops with a classed error that says
# what the package is needed for. Call it at the top of the function that
# uses the package, then call that package's functions with pkg::fun().
check_suggested <- function(pkg, reason, call = rlang::caller_env()) {
  rlang::check_installed(pkg, reason = reason, call = call)
}

# An example user: writes a Markdown table with knitr (a suggested package).
markdown_table <- function(data) {
  rlang::check_installed("knitr", reason = "to format the table as Markdown")
  knitr::kable(data, format = "pipe")
}

# Run only when called as a script (not when sourced by the tests).
if (sys.nframe() == 0L) {
  path <- write_demo_description()
  cat(readLines(file.path(path, "DESCRIPTION")), sep = "\n")
  print(dependency_table(path))

  message("A package in two fields, and one in Depends:")
  desc::desc_set_dep("rlang", "Suggests", file = path)
  desc::desc_set_dep("dplyr", "Depends", file = path)
  print(dependency_problems(path))

  message("A suggested package that is installed:")
  print(markdown_table(head(mtcars[, 1:3], 3)))

  message("A suggested package that is not installed:")
  tryCatch(
    check_suggested("notarealpkg", "to run this example"),
    error = function(e) {
      cat(conditionMessage(e), "\n")
    }
  )
}

Sources

Standards & R manuals

R package development guides

Package documentation

Comparative packaging standards