最近我似乎和合作者分享了很多代码。他们中的许多人是新手/中级R用户,并没有意识到他们必须安装他们还没有的包。

是否有一种优雅的方式来调用installed.packages(),比较那些我正在加载和安装如果丢失?


当前回答

达森·k和我有一个吃豆人包可以很好地做到这一点。包中的p_load函数执行此操作。第一行代码只是为了确保安装了pacman。

if (!require("pacman")) install.packages("pacman")
pacman::p_load(package1, package2, package_n)

其他回答

确定。

您需要比较“已安装的包”和“所需的包”。这非常接近于我用蔓越莓做的事情,因为我需要比较“存储的已知包”和“当前已知的包”,以确定新的和/或更新的包。

就像这样

AP <- available.packages(contrib.url(repos[i,"url"]))   # available t repos[i]

为了获得所有已知的包,模拟调用当前安装的包,并将其与给定的目标包集进行比较。

今天,我偶然发现了rlang包提供的两个方便函数,即is_installed()和check_installed()。

从帮助页面(强调添加):

These functions check that packages are installed with minimal side effects. If installed, the packages will be loaded but not attached. is_installed() doesn't interact with the user. It simply returns TRUE or FALSE depending on whether the packages are installed. In interactive sessions, check_installed() asks the user whether to install missing packages. If the user accepts, the packages are installed [...]. If the session is non interactive or if the user chooses not to install the packages, the current evaluation is aborted.

interactive()
#> [1] FALSE
rlang::is_installed(c("dplyr"))
#> [1] TRUE
rlang::is_installed(c("foobarbaz"))
#> [1] FALSE
rlang::check_installed(c("dplyr"))
rlang::check_installed(c("foobarbaz"))
#> Error:
#> ! The package `foobarbaz` is required.

由reprex包在2022-03-25创建(v2.0.1)

此解决方案将获取包名的字符向量并尝试加载它们,或者在加载失败时安装它们。它依赖于require的返回行为来做到这一点,因为…

Require返回(不可见的)一个逻辑,指示所需的包是否可用

因此,我们可以简单地查看是否能够加载所需的包,如果不能,则使用依赖项安装它。所以给定一个你想要加载的包的字符向量…

foo <- function(x){
  for( i in x ){
    #  require returns TRUE invisibly if it was able to load package
    if( ! require( i , character.only = TRUE ) ){
      #  If package was not able to be loaded then re-install
      install.packages( i , dependencies = TRUE )
      #  Load package after installing
      require( i , character.only = TRUE )
    }
  }
}

#  Then try/install packages...
foo( c("ggplot2" , "reshape2" , "data.table" ) )

达森·k和我有一个吃豆人包可以很好地做到这一点。包中的p_load函数执行此操作。第一行代码只是为了确保安装了pacman。

if (!require("pacman")) install.packages("pacman")
pacman::p_load(package1, package2, package_n)

这就是rbundler包的目的:提供一种方法来控制为特定项目安装的包。现在,这个包使用devtools功能将包安装到项目的目录中。该功能类似于Ruby的捆绑器。

如果你的项目是一个包(推荐),那么你所要做的就是加载rbundler并捆绑包。bundle函数将查看包的DESCRIPTION文件,以确定要捆绑哪些包。

library(rbundler)
bundle('.', repos="http://cran.us.r-project.org")

现在这些包将安装在. rbundle目录中。

如果你的项目不是一个包,那么你可以在项目的根目录中创建一个DESCRIPTION文件,其中包含一个Depends字段,列出你想要安装的包(包括可选的版本信息):

Depends: ggplot2 (>= 0.9.2), arm, glmnet

如果你对这个项目感兴趣,这里是github回购:rbundler。