Automatically install list of packages in R if necessary

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?


Solution 1:

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:

  1. pacman GitHub page
  2. Introduction to pacman

Solution 2:

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)
}