How to install and load multiple missing packages in R?
- How to identify which packages are missing?
- Why is using lapply() to load multiple packages considered bad practice?
- How to load multiple packages?
How to install and load multiple missing packages in R?
I would use the pacman
package. It loads several packages at the same time, and if any of them is not installed it installs them (using the same function). Try it:
install.packages("pacman")
pacman::p_load(tidyverse, ....)
The install.packages()
function accepts a vector of packages to install. You don't need any other package to do this:
install.packages(c("dplyr", "magrittr", "tidyr"))
Dependencies are installed by default. So you don't have to worry about it.
You could use the function search()
to identify which packages are already loaded.
Many of the packages already rely on other packages, but one of the most popular around is the tidyverse
, which is a very useful toolkit that loads a collection of useful packages that are really useful for data importing, data manipulation, graphics, and other activities that work all in sync.
To load the tidyverse
, you would simply call library(tidyverse)
and straight away load the following packages developed by Hadley Wickham:
-- Attaching packages ---------------------------------------------------------------------------------------------- tidyverse 1.3.0 --
v ggplot2 3.3.2 v purrr 0.3.4
v tibble 3.0.4 v dplyr 1.0.2
v tidyr 1.1.2 v stringr 1.4.0
v readr 1.4.0 v forcats 0.5.0
You could use the pkg_attach2
function from xfun
(more information here, under "Loading and attaching packages": https://yihui.org/xfun/):
The function pkg_attach2() is a shorthand of pkg_attach(..., install = TRUE), which means if a package is not available, install it. This function can also deal with multiple packages.
The function loadable() tests if a package is loadable.
This may help :
if (!require("pacman")) install.packages("pacman")
pacman::p_load(package1, package2, package_n)