Check if Package is Missing and Install Automatically (R Programming Example)

 

On this page you’ll learn how to install missing package automatically in the R programming language.

The post contains these topics:

You’re here for the answer, so let’s get straight to the R code.

 

Example: Install Missing Packages Automatically

The following R code checks whether a list of R add-on packages is installed already and installs all packages which are not installed yet (source). The code consists of three lines:

  • In line 1 you need to specify all packages you want to check. For testing, you can simply insert some random CRAN packages of this list.
  • Line 2 identifies all uninstalled packages of the list specified in line 1.
  • Line 3 installs all missing packages.
my_packages <- c("A3", "aaSEA", "abbyyR", "abc")                                        # Specify your packages
not_installed <- my_packages[!(my_packages %in% installed.packages()[ , "Package"])]    # Extract not installed packages
if(length(not_installed)) install.packages(not_installed)                               # Install not installed packages

In case some packages were not installed, the RStudio console typically returns something like this:

 

installation log console r

Figure 1: Installation Messages in RStudio Console.

 

Optionally, you could print the number of installed packages to your RStudio console. Just run the following R syntax:

print(paste(length(not_installed), "packages had to be installed."))                    # Print information to console
# "4 packages had to be installed."

In the present example, four packages were lacking and had to be installed.

 

Video, Further Resources & Summary

I have recently released a video on my YouTube channel, which shows the R programming code of this tutorial. You can find the video below.

 

 

Furthermore, you may want to have a look at the other RStudio tutorials of my website. A selection of articles is shown here.

 

Summary: Do you sometimes wonder how to know if a package is installed in R? In this article, I illustrated how to verify whether an R add-on package is installed and how to install it automatically in an elegant way in case it is not there. In case you have additional questions, let me know in the comments section below. Besides that, don’t forget to subscribe to my email newsletter to get updates on the newest tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top