11.4 Package is listed in Suggests

Recall from Chapter 10:

Packages listed in Suggests are either needed for development tasks or might unlock optional functionality for your users.

You can NOT assume that every user has installed aaapkg (but you can assume that a developer has).

They could be installed through:

  • install.packages("pkg", dependencies = TRUE)

11.4.1 In code below R/

You can check for the availability of a suggested package using requireNamespace("aaapkg", quietly = TRUE)

Two scenarios:

  1. The dependency is required and the function wont work without it
# the suggested package is required 
my_fun <- function(a, b) {
  if (!requireNamespace("aaapkg", quietly = TRUE)) {
    stop(
      "Package \"aaapkg\" must be installed to use this function.",
      call. = FALSE
    )
  }
  # code that includes calls such as aaapkg::aaa_fun()
}
  1. You have a fallback in the function/package if the user does not have the required package
# the suggested package is optional; a fallback method is available
my_fun <- function(a, b) {
  if (requireNamespace("aaapkg", quietly = TRUE)) {
    aaapkg::aaa_fun()
  } else {
    g()
  }
}

rlang has useful functions for checking package availability, offering to install the package for the user and programming (such as vectorization over pkg).

11.4.2 In test code

Including packages from Suggests when writing tests depends on the maintainer/developer.

The tidyverse team generally writes tests as if all suggested packages are available.

  • testthat package is in the Suggests field so we can assume all suggested packages are available

  • They will skip sometimes e.g. if package is cumbersome to install and not already installed

11.4.3 In examples and vignettes

An example is a common place to use a suggested package and is one of the few places we would use require() or requireNamespace() in a package.

A vignette needs packages contained in the Suggests field.

  • Similar to tests, we can assume all suggested packages are available and use suggested packages unconditionally.

  • If you want to use suggested packages conditionally, the knitr chunk option eval can be used (more in a later chapter).