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

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

问题描述

我有一个包含一大堆杂项功能的包(请参阅 如何处理不完善但有用的功能?).因为这些功能不是特别相关,所以它们依赖于一大堆其他包.通常整个包中只有一个函数使用另一个包.然而,如果我在说明文件中使用 Imports、Suggests 或 Depends,则每次加载我的包时都会加载整个包列表,即使任何给定用户需要它们中的很少.

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() ,但这似乎是一种不好的做法,因为它不会告诉包管理系统任何东西,因此用户可能没有安装它.p>

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.

推荐答案

可以使用Suggests,在需要该包的函数中可以添加代码到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天全站免登陆