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

To check if a package is installed in R, you can use the installed.packages() function to list all the packages that are currently installed. You can then use the package name to determine if it is installed on your system. Additionally, you can use the library() or require() functions to check if a package is installed and load it if it is. If the package is not installed, you will get an error message.


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 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 <- c('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.

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

x