1

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?

schustischuster
  • 743
  • 9
  • 29

3 Answers3

1

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))
danlooo
  • 10,067
  • 2
  • 8
  • 22
  • Thanks, but all the packages that were previously installed get loaded at first execution of loadLibrary(), only the one that was not installed and had to be installed does not get loaded at the first execution, only if I run the function again (see session info from the R console output). The newly installed package should be loaded at the first time, I want to avoid the error and don't want to run the function twice. – schustischuster Feb 07 '22 at 18:42
  • @schustischuster I revised my answer – danlooo Feb 07 '22 at 18:48
  • Great - it loads the library now at the first time, but still gives me a warning message (not an error) when trying to load the previously not installed package ‘markdown’: Warning: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, : there is no package called ‘markdown’. Why is that? Of course I could use suppressWarnings(), but would prefer not to do this. – schustischuster Feb 07 '22 at 19:01
  • What do you mean with 'previously uninstalled package'? Of course, there is no package after removal. – danlooo Feb 07 '22 at 19:03
  • Sorry, typo - comment corrected. The package that was not installed previously and gets installed with the function still leads to a warning message "there is no package..." even though it has been installed. – schustischuster Feb 07 '22 at 19:07
  • This is the output: > invisible(lapply(lib_List, loadLibrary)) Lade nötiges Paket: markdown versuche URL 'https://cran.uni-muenster.de/bin/macosx/el-capitan/contrib/3.6/markdown_1.1.tgz' Content type 'application/x-gzip' length 199930 bytes (195 KB) ================================================== downloaded 195 KB The downloaded binary packages are in /var/folders/... Warnmeldung: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, : es gibt kein Paket namens ‘markdown’ – schustischuster Feb 07 '22 at 19:10
  • Please check your `.libPaths()`. Are the libraries being installed in a non standard path? I was able to test my answer using Docker container `rocker/tidyverse:4.1.2`. It worked on this system. Maybe your system went into another state. – danlooo Feb 07 '22 at 19:46
  • Library path is "/Library/Frameworks/R.framework/Versions/3.6/Resources/library" – schustischuster Feb 07 '22 at 19:48
  • Looks like MacOS. I have not used this so far. Sorry. – danlooo Feb 07 '22 at 19:48
  • Yes, it's MacOS. Any idea what I can try to get rid of the warning? – schustischuster Feb 07 '22 at 19:50
  • 1
    Looks like that this warning is linked to the state of your particular system and your environment, thus I can not debug this. I always put my R packages into Docker containers, so they do not interfere so much with the other tools installed on my machine. Containers are one-use boxes with a fixed initial state. They are needed if you want to reproduce subtle warnings and errors. – danlooo Feb 07 '22 at 19:55
1

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

pacman::p_load(dplyr, ggplot2, scales, caret, install = TRUE)
Konrad
  • 17,740
  • 16
  • 106
  • 167
0

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.

schustischuster
  • 743
  • 9
  • 29