Loading Multiple Libraries - 'package' must be of length 1


I am new to Posit and Posit cloud, so was looking for help here.

I am trying to install and load multiple packages like this:

install.packages(c("tidyverse", "ggplot2", "proxy", "e1071", "wk", "classInt", "DBI", "Rcpp", "s2", "units", "sf"))
library(c("tidyverse", "ggplot2", "proxy", "e1071", "wk", "classInt", "DBI", "Rcpp", "s2", "units", "sf"))

However i see an error related to the loading of the packages that says :slight_smile:

Error in library(c("tidyverse", "ggplot2", "proxy", "e1071", "wk", "classInt",  : 
  'package' must be of length 1

Is it not possible to load packages like this once installed?

Thanks in advance - great to be part of the community!

You can use lapply to do this:

lapply(c("tidyverse", "ggplot2", "proxy", "e1071", "wk", "classInt", "DBI", "Rcpp", "s2", "units", "sf"), library, character.only = TRUE)

Thanks Sam! It worked!

Was I trying something that was not possible with the library function? I had not come across lapply() and looked more into its use - it sounds like a workaround for what I was trying to do :slight_smile: or is this an official/recommended way to load multiple packages at once?

Thanks again.

Lapply simply apply the function (library) over the list/vector you provided using c()

Alternatively, we can try the below code

libraries <- c("tidyverse", "ggplot2", "proxy", "e1071", "wk", "classInt", "DBI", "Rcpp", "s2", "units", "sf")

purrr::map(libraries, function(.x) library(.x, character.only = T))

Great thank you both for clarifying :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.