对于我的一个脚本,我想编写一个 R 函数来检查一个包是否已经安装:如果是这样,它应该使用 library() 将它导入命名空间,否则它应该安装并导入它。
我假设pkgname是一个字符串,并尝试编写如下内容:
ensure_library <- function(pkgname) {
if (!require(pkgname)) {
install.packages(pkgname, dependencies = TRUE)
}
require(pkgname)
}
如此简单,此功能不起作用。如果我尝试像ensure_library("dplyr")
安装包 dplyr 一样运行它,但它会失败,因为它尝试导入pkgname
而不是dplyr
在命名空间中。
ensure_library("dplyr")
Loading required package: pkgname
Installing package into ‘/home/luca/R-dev’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/dplyr_0.5.0.tar.gz'
Content type 'application/x-gzip' length 708476 bytes (691 KB)
==================================================
downloaded 691 KB
* installing *source* package ‘dplyr’ ...
** package ‘dplyr’ successfully unpacked and MD5 sums checked
** libs
.... a lot of compiling here....
installing to /home/luca/R-dev/dplyr/libs
** R
** data
*** moving datasets to lazyload DB
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded
* DONE (dplyr)
The downloaded source packages are in
‘/tmp/Rtmpfd2Lep/downloaded_packages’
Loading required package: pkgname
Warning messages:
1: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called ‘pkgname’
2: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called ‘pkgname’
另外,如果我现在重新运行它,它将dplyr
再次安装。
我意识到这可能是由于 R 非标准评估,我尝试了几种 eval/substitute/quote 的组合以使其工作,require
但我无法成功。
有人可以帮助我了解发生了什么以及是否有一些简单的解决方法吗?
如果一个已经实现它的函数存在,我想知道,但我真正感兴趣的是理解为什么我的代码不能按预期工作。