Loading depending packages using .onLoad

2020-03-28 19:46发布

问题:

My package requires ggplot2 package, but I am having trouble to fix the following NOTES that I get when I run R CMD check.

no visible global function definition for qplot
'library' or 'require' call not declared from: ggplot2

I also have a .onLoad function,

.onLoad <- function(libname, pkgname){
.libPaths("~/RLibrary")
require(ggplot2)
}

Any suggestions on how to solve the errors? Where should I place the onLoad function?

Thank you
San

回答1:

I don't think you should do it like that. It is best to either make your package depend on ggplot2 or import the namespace of ggplot2. Do the in the DESCRIPTION file by adding Depends: ggplot2 and the second by adding Imports: ggplot2 in DESCRIPTION and import(ggplot2) in NAMESPACE (or be more exact with importfrom(ggplot2,"somefunction").

Alternatively you could set Suggests: ggplot2 in DESCRIPTION and put a require("ggplot2") in any functions that uses it, but I don't like this alot.

See also:

http://cran.r-project.org/doc/manuals/R-exts.html#The-DESCRIPTION-file

EDIT: To be a bit more clear. With Depends the package is loaded every time your package is loaded and its functions are all available for the user.

With Imports you can use the functions of the package, but the package is not loaded when your package is not loaded (functions are not available to the user).

With Suggests the package is not loaded when you load your package and you can't use its functions. You need to declare a require somewhere to use them. Basically this can be used to make clear that you use this package somewhere (in an example or so).

It all depends on how you want your users to be able to use the depended package and how important it is for your package. For example, if your package is a frontend to ggplot2 Depends is best, if it does some analysis and has an plot function Imports is best.