You should never use library()
or require()
in a package, because they affect the user's search list, possibly causing errors for the user.
For example, both the dplyr
and stats
packages export a function called filter
. If a user had only library(stats)
, then filter
would mean stats::filter
, but if your package called library(dplyr)
, the user might suddenly find that filter
means dplyr::filter
, and things would break.
There are a couple of alternatives for your package. You can import functions from another package by listing it in the Imports:
field in the DESCRIPTION
file and specifying the imports in the NAMESPACE
file. (The roxygen2
package can make these changes for you automatically if you put appropriate comments in your .R
source files, e.g.
#' @importFrom jsonlite toJSON unbox
before a function that uses those to import toJSON()
and unbox()
from the jsonlite
package.)
The other way to do it is using the ::
notation. Then you can still list a package in the Imports:
field of DESCRIPTION
, but use code like
jsonlite::toJSON(...)
every time you want to call it. Alternatively, if you don't want a strong dependence on jsonlite
, you can put jsonlite
in Suggests:
, and wrap any uses of it in code like
if (requireNamespace("jsonlite")) {
jsonlite::toJSON(...)
}
Then people who don't have that package will still be able to run your function, but it may skip some operations that require jsonlite
.