Home > OS >  Error when installing and loading library from list
Error when installing and loading library from list

Time:02-08

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?

CodePudding user response:

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))

CodePudding user response:

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

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