Load Multiple Packages at Once

Load multiple packages at once

Several permutations of your proposed functions do work -- but only if you specify the character.only argument to be TRUE. Quick example:

lapply(x, require, character.only = TRUE)

Loading multiple R packages with a single command

Set character.only on TRUE

Packages <- c("ggplot2", "lme4")
Packages %in% loadedNamespaces() # check if the packages are loaded
# [1] FALSE FALSE

pacman::p_load(Packages, character.only = TRUE)

Packages %in% loadedNamespaces()
# [1] TRUE TRUE

From ?p_load:

"character.only : logical. If TRUE then p_load will only accept a single input which is a character vector containing the names of packages to load."

library() function fails to load multiple packages

The library() function isn't meant to load multiple libraries, a better approach is to create a list of packages, and use require() to check if they are installed and if not install them. See example below:

requiredPackages <- c("MASS", "caret", "stepPlr", "janitor")


ipak <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}

ipak(requiredPackages)

load multiple packages AND supress messages

One option would be

pacman::p_load(packages)

Loading multiple libraries simultaneously

Another way could be using alist with eval and substitute like below:

read_library <- function(...) {
obj <- eval(substitute(alist(...)))
#print(obj)
return(invisible(lapply(obj, function(x)library(toString(x), character.only=TRUE))))
}

read_library(gtools, ggplot2, tidyverse)

alist handles its arguments as if they described function arguments. So the values are not evaluated together with substitute it returns un-evaluated expression. Once we have the expression, we use eval to get a list of objects of class name, so that we can parse it as string in lapply.

How to load multiple packages using a package

.onAttach calls tidyverse_attach() (https://github.com/tidyverse/tidyverse/blob/master/R/zzz.R#L7), which loads packages using library (https://github.com/tidyverse/tidyverse/blob/master/R/attach.R#L37-L39).

Why does loading multiple packages in R produce warnings?

I think the problem is that you used T when you meant TRUE. For example,

    T <- 1:10
require("stats", character.only = T)
#> Warning in if (!character.only) package <- as.character(substitute(package)):
#> the condition has length > 1 and only the first element will be used

Created on 2021-12-27 by the reprex package (v2.0.1)

Remember, T is a variable name in R. You can change its value. It is frequently a source of obscure bugs when you use it instead of the constant value TRUE.



Related Topics



Leave a reply



Submit