简体   繁体   中英

Elegant way to load a string list of packages in R

Hi I've written the following code:

################# Loadin Require Libraries #################
required.packages <- c('caret','readxl')
for (pkg in required.packages){
  if(!require(pkg, character.only = T)){
    install.packages(pkg,
                     character.only = T,
                     dependencies = T)
    library(pkg, character.only = T)
  }else{
    library(pkg, character.only = T)
  }

}

The code shall be ran on a computer of a peer, so to take care of might missing libraries I thought I iterate threw a string list, to check if the package is installed if yes -> load if no -> install and load then. However when a package is not available R still puts out a warning message: Warning message:

In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, : es gibt kein Paket namens 'readxl'

My question: is there a better way to check / install a bunch of libraries in R? Should I care about the warning? If it is not important is there a way to surpress this warning getting printed?

Edit: Final solution Thanks to the correct answer provided by @akrun:

################# Loadin Require Libraries #################
lib <- .libPaths()[1]
required.packages <- c('caret','readxl')
i1 <- !(required.packages %in% row.names(installed.packages()))
if(any(i1)) {
  install.packages(required.packages[i1], dependencies = TRUE, lib = lib) 
}
lapply(required.packages, require, character.only = TRUE)

Update 2021 - Pacman

I found the pacman - package really helpful for exactly this purpose, especially the p_load function . It checks if the package is installed and otherwise tries to install the missing package.

This function is a wrapper for library and require. It checks to see if a package is installed, if not it attempts to install the package from CRAN and/or any other repository in the pacman repository list.

So nowadays I start all my scripts that need to be 'portable' with the following lines:

require(pacman)  
# Load / Install Required Packages
p_load(dplyr, tidyr, gridExtra, psych)

In this case to load / install dplyr , tidyr , gridExtra & psych

Also nice in this package (if you want to clean up the environment) p_unload

# Unload All packages
p_unload()

Here is one option

Pkgs <- c('caret','readxl')
lib <- .libPaths()[1]

i1 <- !(Pkgs %in% row.names(installed.packages()))
if(any(i1)) {
  install.packages(Pkgs[i1], dependencies = TRUE, lib = lib) 
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM