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

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


当前回答

pckg=c("shiny","ggplot2","dplyr","leaflet","lubridate","RColorBrewer","plotly","DT","shinythemes")

for(i in 1:length(pckg)) 
   {
      print(pckg[i])
      if (!is.element(pckg[i], installed.packages()[,1]))
      install.packages(pckg[i], dep = TRUE)
      require(pckg[i], character.only = TRUE)
}

其他回答

source("https://bioconductor.org/biocLite.R")
if (!require("ggsci")) biocLite("ggsci")

让我分享一点疯狂:

c("ggplot2","ggsci", "hrbrthemes", "gghighlight", "dplyr") %>%  # What will you need to load for this script?
  (function (x) ifelse(t =!(x %in% installed.packages()), 
    install.packages(x[t]),
    lapply(x, require))) 

上面的许多答案(以及这个问题的副本)依赖于安装。包装是不好的形式。从文档中可以看到:

当安装了数千个包时,这可能会很慢,所以不要使用它来查找是否安装了指定的包(使用system. exe)。或者查找一个包是否可用(调用require并检查返回值),或者查找少量包的详细信息(使用packageDescription)。每个安装的包需要读取几个文件,这在Windows和一些网络挂载的文件系统上会很慢。

因此,更好的方法是尝试使用require和install加载包,如果加载失败(如果没有找到require将返回FALSE)。我更喜欢这样的实现:

using<-function(...) {
    libs<-unlist(list(...))
    req<-unlist(lapply(libs,require,character.only=TRUE))
    need<-libs[req==FALSE]
    if(length(need)>0){ 
        install.packages(need)
        lapply(need,require,character.only=TRUE)
    }
}

可以这样使用:

using("RCurl","ggplot2","jsonlite","magrittr")

通过这种方式,它加载所有的包,然后返回并安装所有丢失的包(如果您愿意,可以在这里插入提示,询问用户是否想要安装包)。而不是调用install。对于每个包,它只传递一次卸载包的整个向量。

下面是相同的函数,但是有一个窗口对话框,询问用户是否想要安装缺少的包

using<-function(...) {
    libs<-unlist(list(...))
    req<-unlist(lapply(libs,require,character.only=TRUE))
    need<-libs[req==FALSE]
    n<-length(need)
    if(n>0){
        libsmsg<-if(n>2) paste(paste(need[1:(n-1)],collapse=", "),",",sep="") else need[1]
        print(libsmsg)
        if(n>1){
            libsmsg<-paste(libsmsg," and ", need[n],sep="")
        }
        libsmsg<-paste("The following packages could not be found: ",libsmsg,"\n\r\n\rInstall missing packages?",collapse="")
        if(winDialog(type = c("yesno"), libsmsg)=="YES"){       
            install.packages(need)
            lapply(need,require,character.only=TRUE)
        }
    }
}

此解决方案将获取包名的字符向量并尝试加载它们,或者在加载失败时安装它们。它依赖于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" ) )

下面这个简单的函数非常好用:

  usePackage<-function(p){
      # load a package if installed, else load after installation.
      # Args:
      #   p: package name in quotes

      if (!is.element(p, installed.packages()[,1])){
        print(paste('Package:',p,'Not found, Installing Now...'))
        install.packages(p, dep = TRUE)}
      print(paste('Loading Package :',p))
      require(p, character.only = TRUE)  
    }

(不是我的,一段时间前在网上找到了这个,从那时起就一直在使用它。不确定原始来源)