Check if R package is installed then load library

前端 未结 6 952
半阙折子戏
半阙折子戏 2020-12-15 07:49

Our R scripts are used on multiple users on multiple computers and hence there are deviations in which packages are installed on each computer. To ensure that each script wo

6条回答
  •  情歌与酒
    2020-12-15 08:23

    Though @maloneypatr function works fine, but it is quite silent and does not respond on success of packages loaded. I built below function that does make some checks on user entry and also respond on the number of packages being successfully installed.

    lubripack <- function(...,silent=FALSE){
    
      #check names and run 'require' function over if the given package is installed
      requirePkg<- function(pkg){if(length(setdiff(pkg,rownames(installed.packages())))==0)
                                        require(pkg, quietly = TRUE,character.only = TRUE)
                                }
    
      packages <- as.vector(unlist(list(...)))
      if(!is.character(packages))stop("No numeric allowed! Input must contain package names to install and load")
    
      if (length(setdiff(packages,rownames(installed.packages()))) > 0 )
         install.packages(setdiff(packages,rownames(installed.packages())),
                          repos = c("https://cran.revolutionanalytics.com/", "http://owi.usgs.gov/R/"))
    
      res<- unlist(sapply(packages, requirePkg))
    
      if(silent == FALSE && !is.null(res)) {cat("\nBellow Packages Successfully Installed:\n\n")
                        print(res)
                       }
    }
    

    Note 1:

    If silent = TRUE(all capital silent), it installs and loads packages without reporting. If silent = FALSE, it reports successful installation of packages. Default value is silent = FALSE

    How to use

    lubripack(“pkg1","pkg2",.,.,.,.,"pkg")
    

    Example 1: When all packages are valid and mode is not silent

    lubripack(“shiny","ggvis")
    

    or

    lubripack(“shiny","ggvis", silent = FALSE)
    

    Output

    Example 2: When all packages are valid and mode is silent

    lubripack(“caret","ggvis","tm", silent = TRUE) 
    

    Output 2

    Example 3: When package cannot be found

    lubripack(“shiny","ggvis","invalidpkg", silent=FALSE) 
    

    Output 3


    How to Install Package:

    Run below code to download the package and install it from GitHub. No need to have GitHub Account.

    library(devtools)
    install_github("espanta/lubripack")
    

提交回复
热议问题