Home » How to Check if a Package is Installed in R (With Example)

How to Check if a Package is Installed in R (With Example)

by Tutor Aspire

You can use the following methods to check if a package is installed in R:

Method 1: Check if Particular Package is Installed

#check if ggplot2 is installed
system.file(package='ggplot2')

Method 2: Install All Packages in a Vector that are Not Already Installed

install.packages(setdiff(packages, rownames(installed.packages())))  

In this example, packages represents a vector of package names you’d like to have installed.

The following examples show how to use each method in practice.

Example 1: Check if Particular Package is Installed

We can use the system.file() function to check if a particular package is installed in current R environment.

For example, we can use the following syntax to check if the package ggplot2 is installed in the current R environment:

#check if ggplot2 is installed
system.file(package='ggplot2')

[1] "C:/Users/bob/Documents/R/win-library/4.0/ggplot2"

Since ggplot2 is installed, the function simply returns the file path to where the package is installed.

Now suppose we check if a package called this_package is installed:

#check if this_package is installed
system.file(package='this_package')

[1] ""

The function returns an empty string, which tells us that the package called this_package (which doesn’t even exist) is not installed in our current environment.

Method 2: Install All Packages in a Vector that are Not Already Installed

Suppose we would like to check if the following three packages are installed in our current environment and automatically install them if they are not:

  • ggplot2
  • dplyr
  • lattice

The following code shows how to do so:

#define packages to install
packages ggplot2', 'dplyr', 'lattice')

#install all packages that are not already installed
install.packages(setdiff(packages, rownames(installed.packages())))

If any of the packages that we specified are not already installed, the install.packages() function will automatically install them.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Load Multiple Packages in R
How to Clear the Environment in R
How to Clear All Plots in RStudio

You may also like