5

My goal is to create R package which use other library such as grid and ggplot2.
According to https://tinyheero.github.io/jekyll/update/2015/07/26/making-your-first-R-package.html, it is said that library() or require() should not be used in a R package.

My questions are:
1)Is there a reason? (because, although I put library("ggplot2") and library("grid") in my R script in my package, it still worked).
2)Do I have to delete library("ggplot2") and library("grid") in my code and put "::" such as ggplot2::geom.segment()?

Is there an efficient way to convert script to the one for package?

Dave2e
  • 22,192
  • 18
  • 42
  • 50
Soon
  • 491
  • 3
  • 16

1 Answers1

7

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.

user2554330
  • 37,248
  • 4
  • 43
  • 90