0

Instead of loading 30 packages each with the library function is it possible to do this in a loop?

pckgs = c("readr", "dplyr")
sapply(pckgs, library)

Background:

Before loading, i test if the packages are installed. For doing so i already have the package names in the form of c("readr", ..., "dplyr") and was wondering if i can also load the package in a loop instead of writing 30 times library().

What i tried:

I simplified to one package:

sapply("readr", library)
sapply("readr", function(lib) library(lib))
sapply("readr", function(lib) library(get(lib)))

Spoiler:

I wanted to post this question and then decided to check for a "force character" in the parameter and got lucky. (It is a bit weird asking a question and answering it yourself, but when i read this i felt motivated enough :) https://stackoverflow.com/help/self-answer

Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59

1 Answers1

4

The parameter character.only can be used for that.

Example:

pckgs = c("readr", "dplyr")
sapply(pckgs, library, character.only = TRUE)
Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59