try explicitly loading required packages in ./R/zzz.R
in the onLoad
function. For example:
.onLoad <- function(libname, pkgname) {
invisible(suppressPackageStartupMessages(
sapply(c("tibble", "purrr", "dplyr", "tidyr", "ggplot2", "data.table"),
requireNamespace, quietly = TRUE)
))
}
(BTW: I used sapply
here for laziness, not that it adds much to things. It could easily have been a for
loop with no consequence.)
For a discussion about the use of requireNamespace
in place of library
, see "library vs require", and "Writing R Extensions" where it states
R code in the package should call library or require only exceptionally. Such calls are never needed for packages listed in ‘Depends’ as they will already be on the search path. It used to be common practice to use require calls for packages listed in ‘Suggests’ in functions which used their functionality, but nowadays it is better to access such functionality via :: calls.
What we are doing is technically not required, but I think by forcing doing it this way, it is encouraging more-silent operation. (This rides on the coat-tails of
Notice that I used suppressPackageStartupMessages
. "Courteous" package maintainers use packageStartupMessage
instead of message
for their loading messages: the latter takes a bit more work and is much less discriminant than the former, which is very easily suppressed without unintended consequences. There are many packages that do not do this, for which I think it's fair to submit a PR to fix.
Another comment about requireNamespace
: this means that the functions in those packages will not be in the search path of the R sessions. If the user will always be using certain packages (e.g., data.table
or dplyr
), then you might want to explicitly load them with library
. From "Writing R Extensions" again:
Field ‘Depends’ should nowadays be used rarely, only for packages which are intended to be put on the search path to make their facilities available to the end user (and not to the package itself): for example it makes sense that a user of package latticeExtra would want the functions of package lattice made available.
However, if you're being good about your package, then you are using ::
notation for all non-base packages anyway. There are certainly ways you can get around using ::
, but (1) CRAN checks are rather intense at times, (2) explicit is usually "A Good Thing (tm)", and (3) it can actually make maintainability much easier (such as when a dependent package changes their API/ABI and you need to check all calls to their package, where searching for pkgname::
is much easier than searching for each of their functions individually).