How to automatically install an uninstalled R package?

Why install automatically R libraries?

During the R script conception, we often call libraries not set on the basic packages.

Problem: your environment doesn't have the same libraries as that of your users or your other workstation. Rather than cumulate errors when you launch your script, here is a command to automatically install your libraries / packages missing in RStudio.

packages <- c("myPackage", "myOtherPackage")
newPackages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(newPackages)) install.packages(newPackages)

Regroup the packages used on the script

The first line regroups the libraries called on your script. We can find them on the packages object that contain the following vector:

packages <- c("myPackage", "myOtherPackage")

Installed packages check

Then, we will use the installed.packages() function to identify the libraries installed on your workstation. This function sends a data frame which contain the specifications of each installed library.

On the Package column, we will check that our needed packages are installed. Each package unlisted (not visible on this data frame) is added to the newPackages object with the following line.

packages[!(packages %in% installed.packages()[,"Package"])]

Missing packages installation

Now, you just have to automatically install the missing libraries. We will check that the newPackages object length isn't equal to 0, that mean there is no new package to install.

If newPackages isn't empty, we launch the installation of the new packages, contained on the newPackages object.

if(length(newPackages)) install.packages(newPackages)

Your libraries are now installed, you can launch your script without errors generated by missing packages.