You can install multiple packages by passing a vector of package names to the function, for example, install. packages(c("dplyr", "stringr")) . That function will install the requested packages, along with any of their non-optional dependencies.
As explained in Example 1, the major difference between library and require is that library returns an error and require returns a warning in case a package is not installed yet.
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)
The CRAN package pacman that I maintain (authored with Dason Kurkiewicz) can accomplish this:
So the user could do:
## install.packages("pacman")
pacman::p_load(dplyr, psych, tm)
and if the package is missing p_load
will download it from CRAN or Bioconductor.
This should do the trick:
lapply(x, FUN = function(X) {
do.call("require", list(X))
})
(The key bit is that the args
argument in do.call(what, args)
must be a list --- even if it only has a single element!)
For someone who wants to install and load packages simultaneously I came across this function from this link
# ipak function: install and load multiple R packages.
# check to see if packages are installed. Install them if they are not, then load them into the R session.
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)
}
# usage
packages <- c("ggplot2", "plyr", "reshape2", "RColorBrewer", "scales", "grid")
ipak(packages)
An alternative option comes from the package easypackages
. Once installed, you can load packages in the most intuitive way:
libraries("plyr", "psych", "tm")
The package also includes a function to install several packages:
packages("plyr", "psych", "tm")
Reference here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With