schustischuster
schustischuster

Reputation: 761

Error when installing and loading libraries from list in R

I have a function that loads libraries from a list, and installs packages if required:

# List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) { 
    if (!require(x, character.only = T)) {
        install.packages(x)
        library(x)
    }
}

# Load packages
invisible(lapply(lib_List, loadLibrary))

For example, in this case library "caret" is not installed. Running the loadLibrary function, the package gets downloaded and installed but this is followed by an error and the library is not loaded. Below the output from the R console:

Load required package: caret
--- Please select a CRAN mirror for use in this session ---
# Now download notifications follow
The downloaded binary packages are in
    /var/folders/8p/b3t6spn133z5s69hpj1hf4hc0000gn/T//Rtmp8VNEII/downloaded_packages

Error in library(x) : there is no package called ‘x’
In addition: Warning:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘caret’

sessionInfo()
other attached packages:
[1] scales_1.1.1   ggplot2_3.3.5   dplyr_1.0.7  

If I now run the loadLibrary function again, the new installed package gets loaded:

invisible(lapply(lib_List, loadLibrary))
Load package: caret

sessionInfo()
other attached packages:
[1] caret_6.0-90   lattice_0.20-45   scales_1.1.1    ggplot2_3.3.5   dplyr_1.0.7   

Why is the package not loaded the first time I run the loadLibrary function?

Upvotes: 1

Views: 2212

Answers (3)

schustischuster
schustischuster

Reputation: 761

I found that the following modified version, which is based on this answer and another post, will install all missing packages and load them without giving a warning:

# List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

# Install missing packages
instpack <- lib_List %in% installed.packages()[,"Package"]
if (any(instpack == FALSE)) {
  install.packages(lib_List[!instpack])
}

# Load packages
invisible(lapply(lib_List, library, character.only = TRUE))

It's not the shortest solution, but the advantage is that no additional packages are required.

Upvotes: 0

Konrad
Konrad

Reputation: 18585

Consider using pacman. You can achieve the same outcome with one line using p_load:

pacman::p_load(dplyr, ggplot2, scales, caret, install = TRUE)

Upvotes: 1

danlooo
danlooo

Reputation: 10627

You need to always load the library but only install them if they are missing:

# List of required packages
lib_List <- c("dplyr", "ggplot2", "scales", "caret")

loadLibrary <- function(x) { 
  if (!require(x, character.only = TRUE)) {
    install.packages(x)
  }
  # always load
  library(x, character.only = TRUE)
}

# Load packages
invisible(lapply(lib_List, loadLibrary))

Upvotes: 1

Related Questions