最近我似乎和合作者分享了很多代码。他们中的许多人是新手/中级R用户,并没有意识到他们必须安装他们还没有的包。
是否有一种优雅的方式来调用installed.packages(),比较那些我正在加载和安装如果丢失?
最近我似乎和合作者分享了很多代码。他们中的许多人是新手/中级R用户,并没有意识到他们必须安装他们还没有的包。
是否有一种优雅的方式来调用installed.packages(),比较那些我正在加载和安装如果丢失?
当前回答
library <- function(x){
x = toString(substitute(x))
if(!require(x,character.only=TRUE)){
install.packages(x)
base::library(x,character.only=TRUE)
}}
这适用于不带引号的包名,并且相当优雅(参见GeoObserver的答案)
其他回答
今天,我偶然发现了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)
是的。如果您有软件包列表,请将其与installed.packages()[,"Package"]的输出进行比较,然后安装缺少的软件包。就像这样:
list.of.packages <- c("ggplot2", "Rcpp")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
否则:
如果您将代码放在包中并使它们成为依赖项,那么当您安装包时,它们将自动安装。
非常基本的一个。
pkgs = c("pacman","data.table")
if(length(new.pkgs <- setdiff(pkgs, rownames(installed.packages())))) install.packages(new.pkgs)
当前版本的RStudio(>=1.2)包含了一个功能,可以检测library()和require()调用中缺失的包,并提示用户安装它们:
检测丢失的R包 许多R脚本打开时调用library()和require()来加载执行所需的包。如果您打开一个R脚本,该脚本引用了您没有安装的包,RStudio现在将提供一次单击即可安装所有所需的包。不再重复输入install.packages(),直到错误消失! https://blog.rstudio.com/2018/11/19/rstudio-1-2-preview-the-little-things/
这似乎很好地解决了OP最初的问题:
他们中的许多人是新手/中级R用户,并没有意识到他们必须安装他们还没有的包。
下面是我的代码:
packages <- c("dplyr", "gridBase", "gridExtra")
package_loader <- function(x){
for (i in 1:length(x)){
if (!identical((x[i], installed.packages()[x[i],1])){
install.packages(x[i], dep = TRUE)
} else {
require(x[i], character.only = TRUE)
}
}
}
package_loader(packages)