仅在R包中需要时才加载包 [英] Load a package only when needed in R package

查看:109
本文介绍了仅在R包中需要时才加载包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包,其中包含许多其他功能(请参阅

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.

有什么方法可以仅在使用特定函数时才加载依赖项吗?我可以在函数内部调用library(),但这似乎是一种不好的做法,因为它没有告诉包管理系统任何信息,因此用户可能没有安装它.

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.

推荐答案

您可以使用建议",并且在需要该软件包的函数中,可以向require()所述软件包中添加代码,如果不可用,则会引发错误.我熟悉的一个示例vegan包的描述中有

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

sessionInfo()报告没有建议的软件包尚未加载/附加,等等:

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

这篇关于仅在R包中需要时才加载包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆