Reputation: 173
I would like to check, at the beginning of my R script, whether the required packages are installed and, if not, install them.
I would like to use something like the following:
RequiredPackages <- c("stockPortfolio","quadprog")
for (i in RequiredPackages) { #Installs packages if not yet installed
if (!require(i)) install.packages(i)
}
However, this gives me error messages because R tries to install a package named 'i'. If instead I use...
if (!require(i)) install.packages(get(i))
...in the relevant line, I still get error messages.
Anybody know how to solve this?
Upvotes: 7
Views: 3986
Reputation: 340
I think this is close to what you want:
requiredPackages <- c("stockPortfolio","quadprog")
for (package in requiredPackages) { #Installs packages if not yet installed
if (!requireNamespace(package, quietly = TRUE))
install.packages(package)
}
HERE is the source code and an explanation of the requireNamespace
function.
Upvotes: 3
Reputation: 173
I have by now written the following function (and put it into a package), which essentially does what @Thomas and @federico propose:
SPLoadPackages<-function(packages){
for(fP in packages){
eval(parse(text="if(!require("%_%fP%_%")) install.packages('"%_%fP%_%"')"))
eval(parse(text="library("%_%fP%_%")"))
}
}
Upvotes: 0
Reputation: 9051
Although the problem has been solved by @Thomas's answer, I would like to point out that pacman
might be a better yet simple choice:
First install pacman:
install.packages("pacman")
Then load packages. Pacman will check whether each package has been installed, and if not, will install it automatically.
pacman::p_load("stockPortfolio","quadprog")
That's it.
Relevant links:
Upvotes: 6
Reputation: 44525
Both library
and require
use non-standard evaluation on their first argument by default. This makes them hard to use in programming. However, they both take a character.only
argument (Default is FALSE
), which you can use to achieve your result:
RequiredPackages <- c("stockPortfolio","quadprog")
for (i in RequiredPackages) { #Installs packages if not yet installed
if (!require(i, character.only = TRUE)) install.packages(i)
}
Upvotes: 2