I've got a package which a whole bunch of miscellaneous functions (see What to do with imperfect-but-useful functions? ). Because the functions are not particularly related, they depend on a whole bunch of other packages. Often there will be just one function in the whole package which uses another package. Yet if I use Imports, Suggests, or Depends in the DESCRIPTION file, the whole list of packages will be loaded each time my package is loaded, even though very few of them are needed by any given user.
Is there any way to just load the dependencies only when a particular function is used? I could put a call to library()
inside the function themselves, but that seems like bad practice since it doesn't tell the package management system anything and therefore the user might not have it installed.
In general, I try to avoid using
require()
in packages. As a suggestion, work with a namespace (that's not difficult) and useImports
: packages mentioned there are not loaded. You can import only a single function from another package by :importFrom
declaration in the namespace file.importFrom(foo, x, y)
tells that functionsx
andy
from package foo should be imported.foo::bar
imports functionbar
from packagefoo
. eg.plyr::ddply(...)
will access the ddply function without the package is loadedfoo:::bar
)In all three cases, the packages should be mentioned in Imports. See also the relevant chapter 1.6 and others in Writing R Extensions.
EDIT : As @Gavin pointed out, this all works only when importing from a package with an own namespace apparently. From next version of R on (2.14?) all packages should have a namespace.
You can use Suggests, and in the function that needs the package you can add code to
require()
said package and if not available throw an error. An example I am familiar with, the vegan package, has, in its DESCRIPTIONand on loading the package we have:
and
sessionInfo()
reports that none of the Suggested packages has yet been loaded/attached etc: