11.3 Package is listed in Imports

Recall from Chapter 10:

Imports are needed by your users at runtime and will be installed (or potentially updated) when users install your package via install.packages()

Your package can assume a package listed in Imports is installed whenever itself is installed.

11.3.1 In code below R/

Recommendation: use the syntax package::function() to:

  • avoid importing package to your namespace
  • easily identify what functions live outside your package
  • eliminate name conflicts

Exceptions:

  • An operator can’t be called with ::. ex: magrittr pipe
  • A function you use a lot: makes code more readable
  • A function used in a tight loop: :: has minor performance penalty on order of 100ns

If making an exception, generate roxygen tag with usethis::use_import_from() and place either:

  • as close as possible to usage of external function
  • in a central location

usethis::use_import_from() updates documentation and calls load_all()

Importing entire package namespace should be rare and is least recommended.

  • example is rlang in tidyverse

  • generally only done when you rely heavily on functions from another package

  • makes code harder to read

  • increases risk of function name conflicts

11.3.2 How to not use a package in Imports

Sometimes you have a package listed in Imports but R thinks you don’t use it

e.g., you only use aaapkg to call aaapkg::aaa_fun() in the default for a function argument in your package

This leads to R CMD check giving the following note:

checking dependencies in R code ... NOTE Namespace in Imports field not imported from: 'aaapkg' All declared Imports should be used.

To get around this, create a function in a file below R/ directory:

  • This function doesn’t need to be called.

  • It shouldn’t be exported

For example:

ignore_unused_imports <- function() {
  aaapkg::aaa_fun()
}

This is preferable to importing the aaapkg::aaa_fun() into your namespace as this will cause aaapkg to be loaded whenever your package is loaded. It is good practice to minimise the loading of packages until it is actually needed.

11.3.3 In test code

Generally, external functions in a test are referred to in the same way as code below R/

  • Call aaapkg::aaa_fun()

Using library(aaapkg) in your tests is usually a bad idea:

  • It makes the search paths for your tests different to how your package works (more in Chapter 15)

11.3.4 In examples and vignettes

If you use a package listed in Imports in your example/vignette either:

  • attach the package with library(aaapkg), or,

  • use a aaapkg::aaa_fun() call