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:
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.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you may want to have a look at the other RStudio tutorials of my website. A selection of articles is shown here.
- Find Out Which Package Version is Loaded in R
- Load Multiple Packages at Once in R
- Unload Package without Restarting R
- Introduction to the pacman Package in R
- R Functions List (+ Examples)
- The R Programming Language
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.
Statistics Globe Newsletter