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.
You only need to install packages the first time you use R (or after updating to a new version). **R Tip:** You can just type this into the command line of R to install each package. Once a package is installed, you don't have to install it again while using the version of R!
The require() is designed to be used inside functions as it gives a warning message and returns a logical value say, FALSE if the requested package is not found and TRUE if the package is loaded. It is better to use the library() as it gives the error message if the package is not found during the package loading time.
Order of Loading Packages in RIn most cases R doesn't care about the order in which packages are loaded. There are some exceptions however, where we've to be careful about how we load packages. If two packages use the same function name, then the package loaded last will hide the function from earlier packages.
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 DESCRIPTION
Depends: permute
Suggests: MASS, mgcv, lattice, cluster, scatterplot3d, rgl, tcltk
and on loading the package we have:
R> require(vegan)
Loading required package: vegan
Loading required package: permute
This is vegan 1.90-0
and sessionInfo()
reports that none of the Suggested packages has yet been loaded/attached etc:
R> sessionInfo()
R version 2.13.1 Patched (2011-07-29 r56550)
Platform: x86_64-unknown-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_GB.utf8 LC_NUMERIC=C
[3] LC_TIME=en_GB.utf8 LC_COLLATE=en_GB.utf8
[5] LC_MONETARY=C LC_MESSAGES=en_GB.utf8
[7] LC_PAPER=en_GB.utf8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_GB.utf8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] vegan_1.90-0 permute_0.5-0
loaded via a namespace (and not attached):
[1] tools_2.13.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With