How to install packages in R?

Install R package from the available sources (CRAN, Bioconductor, GitHub and R-Forge)

An R package is a library of functions that have been developed to cover some needs or specific scientific methods that are not implemented in base R. The functions that R provides by default are limited, so you might be wondering how to install new packages in R. In this tutorial we will review all the sources available to install R packages.

Quick answer

To install a package in R, call install.packages() with the package name in quotes. Then load it with library() every time you start a new session.

install.packages("ggplot2")  # Install once (from CRAN)
library(ggplot2)             # Load it in each session

# Several packages at once
install.packages(c("ggplot2", "dplyr"))

# Packages from GitHub
install.packages("remotes")
remotes::install_github("tidyverse/ggplot2")

You only need to install a package once, but you have to load it with library() in every new R session.

Installing R packages from CRAN

The Comprehensive R Archive Network (CRAN) is the official R packages repository, with thousands of free R packages available. Most of them have been developed by Data Scientists, Statisticians, Professors and researchers. There are all types of packages, from graphics packages as the well-known ggplot2 to very specific topics like the DTDA.cif package, that implements estimators for cumulative incidences of competing risks under double-truncation.

CRAN is the official R repository. All packages have been tested automatically and meet the CRAN policy.

First, you need to look for the name of the package you want to install. You may want to research for your topic googling something like: ‘graphics package R’ or ‘R package for time series’. You can also use the CRAN Task Views, where you can find the most relevant R packages by topic.

Take care! Just because a package is in CRAN does not imply that the methods are well implemented, since there are no third-party checks on this. Also, there may be errors that have not been checked. If you find any type of error or problem, contact the maintainer of the package.

Function to install R packages

Once you decided what package to install, just call the install.packages function with the name of the package inside the parenthesis with quotation marks. As an example, we are going to install the calendR package, that allows creating monthly and yearly calendars, but you can install the package you prefer.

install.packages("calendR")

After installation, you need to load the package if you want to access its functions. For that purpose, you can load it with the library function, specifying the package name with or without quotation marks.

library(calendR)
library("calendR") # Equivalent

Once loaded, you can use ? or the help function with the package name or the name of any function to see the documentation. You will also find useful examples to understand how the package works.

help("calendR")
help(calendR) # Equivalent
?calendR      # Equivalent

# Help for the main function
help(calendR) 

Where are R packages installed?

You can find out where the packages are going to be installed calling the .libPaths() function.

.libPaths() # Returns the installation path of the libraries
[1] "C:/Users/Usuario/AppData/Local/R/win-library/4.3"
[2] "C:/Program Files/R/R-4.3.2/library"

The first path is your personal library and the second one is the library that comes with R. New packages are installed in the first path. If you want to install a package in a different folder, use the lib argument of install.packages and load it with the lib.loc argument of library.

install.packages("calendR", lib = "C:/my_R_library")
library(calendR, lib.loc = "C:/my_R_library")

Note that the libraries depend on the R version (4.3 in the example above). This is why after updating R you will need to reinstall your packages. Check how to update R for more details.

Installing the CRAN packages with the menu

Alternatively, you can install R packages from the menu.

  • In RStudio go to Tools → Install Packages and in the Install from option select Repository (CRAN) and then specify the packages you want.
  • In classic R IDE go to Packages → Install package(s), select a mirror and install the package.

Installing packages in R from zip source

You may have downloaded a package in zip or tar.gz format. In order to install the package from a local zip file you just need to call the install.packages function with arguments repos = NULL and type = "source". Note that the file path mustn’t contain spaces.

install.packages("file_path\\package_file_name.extension",
                 repos = NULL, type = "source")

You can also set your working environment first with the setwd function to the folder where you have downloaded the package file and then install the package specifying the name of the zip or tar.gz file.

setwd("file_path")
install.packages("package_file_name.extension",
                 repos = NULL, type = "source")

The last option is to use the menu. Go to Tools → Install Packages and in the Install from option choose Package Archive File (.zip; .tar.gz) and select your file.

In case you have the zip hosted in some URL you can use the install.packages.zip function from the installr package. Note you can also install packages from CRAN (even older versions) this way.

# install.packages("installr")

library(installr)
install.packages.zip("https://cran.r-project.org/bin/windows/contrib/r-release/calendR_1.0.zip")

Install multiple packages at once

If you need to install several packages at once without writing the same function over and over again, you can make use of the c function within the install.packages function. Note that now the quotation marks are needed to specify the packages names.

install.packages(c("ggplot2", "dplyr"))

Now you know how to install R CRAN packages, but sometimes there are not all in CRAN for many reasons: CRAN has a code policy and some developers don’t want to spend time fixing minor issues to meet those requirements. Other times there exists a development version in GitHub of a CRAN package with additional features you may want. In the following sections you will learn how to install packages from other available sources.

In the following sections we will show you how to install unofficial source packages, but keep in mind that certain packages may be in a development process and could lead to unexpected errors sometimes.

Install R packages from GitHub or GitLab

GitHub is a well-known code sharing platform. If you go to the page, you can search for R packages using the search bar and writing something like: plot package language:R in case you want to look for graphics packages. Note that “language: R” is a search command of the page to restrict the results to only R code repositories. Suppose, for instance, that you want to download the development version of the ggplot2 package from GitHub. The URL would look like:

https://github.com/tidyverse/ggplot2

The first step is to install and load the devtools package, available in CRAN. If you encounter an error while installing it, you probably also need to install Rtools (Windows) or the developer tools of your system.

install.packages("devtools")
library(devtools)

Then you can call the install_github function with "account_name/repository_name" as argument to install the R package from GitHub.

# Installing ggplot2 from GitHub
install_github("tidyverse/ggplot2")

It is worth mentioning that if you don’t want to load the devtools every time you want to install a GitHub package you can use devtools::install_github(account_name /repository_name). The :: operator allows you to call functions from a package without the need of loading it.

Install from GitHub with remotes or pak

devtools is a large package. Its install_github function actually comes from the remotes package, which is much lighter and is the recommended way to install packages from GitHub nowadays.

install.packages("remotes")
remotes::install_github("tidyverse/ggplot2")

# A specific branch, tag or commit
remotes::install_github("tidyverse/ggplot2@v3.4.4")

# Packages hosted on GitLab or Bitbucket
remotes::install_gitlab("account_name/repository_name")
remotes::install_bitbucket("account_name/repository_name")

A modern alternative is the pak package. Its pak function installs packages from CRAN, Bioconductor or GitHub with the same syntax, it is faster and it resolves the dependencies before installing anything.

install.packages("pak")

pak::pak("ggplot2")            # From CRAN
pak::pak("tidyverse/ggplot2")  # From GitHub ("account_name/repository_name")

If the package contains C, C++ or Fortran code, you will need Rtools (Windows) or Xcode command line tools (macOS) to install it from GitHub, as the package has to be compiled.

Install a specific version of a package

Sometimes you need an older version of a package, for instance to reproduce an old analysis or because the latest version requires a newer R version. You can use the install_version function from the remotes package, that downloads the version from the CRAN archive.

remotes::install_version("ggplot2", version = "3.4.4")

# Equivalent with pak
pak::pak("ggplot2@3.4.4")

Then you can check the installed version with packageVersion.

packageVersion("ggplot2")
[1] '4.0.3'

Note that old versions are installed from source, so if the package contains compiled code you will need Rtools (Windows) or the developer tools of your system.

Install R packages from R-Forge

R Forge project is a web with package development tools and repositories. As an example, if you would like to install the MPAgenomics package, you have to specify in the repos argument of the install.packages function the URL of the R Forge project. The dependencies argument is used when repos is not NULL, to specify whether the dependencies of the package that are not installed must be installed or not.

install.packages("MPAgenomics", repos = "http://R-Forge.R-project.org",
                 dependencies = TRUE)

Install bioconductor packages in R

Bioconductor is another project that hosts tools and R packages for analyzing biological data. First, you need to install the BiocManager package.

install.packages("BiocManager")

Second, you can make use of the install function of the package.

# Installing the nanotatoR package
BiocManager::install("nanotatoR") 

Note you can also install more than one package at the same time:

# Installing NBSplice and ncdfFlow packages at once
BiocManager::install(c("NBSplice", "ncdfFlow")) 

It is worth mentioning that you can see the full list of Bioconductor packages in R writing BiocManager::available(). For more information about the Bioconductor installation process refer to the official Bioconductor R packages page.

Install R package in Jupyter Notebook

If you are using R under the conda environment with Jupyter Notebook and you need more packages that the included like ‘Essentials’, you need to specify the repos argument as follows:

install.packages("ggplot2", repos = "http://cran.us.r-project.org")

Update R packages

Updating R packages can be tedious if you have to reinstall the packages over and over again when some has a newer version. You can see the full list of your R packages that are not up-to-date with the old.packages function.

old.packages()

You can update some of them with the install.packages function or calling the update.packages function. If you set the argument ask to FALSE, you will avoid R displaying prompting messages.

update.packages()
update.packages(ask = FALSE)

You will only be able to update a package if it is not loaded. If you have already loaded a package and you want to update it, use the detach function as follows: detach(package:some_package, unload = TRUE)

List functions in R package

Once installed, you can get a list of all the functions in the package. If the package is on CRAN, you will find documentation in PDF format of all functions inside a page like https://cran.r-project.org/web/packages/package_name. Recall you can access this documentation in HTML format with the help function.

help(package = ggplot2)

You can also use the lsf.str or ls commands to list all the functions inside an attached (loaded) package.

lsf.str("package:ggplot2")
ls("package:ggplot2")

Another option is to write: package_name:: and a list will show up in RStudio as a dropdown. In classic R you will have to press the tab button to show the functions on the screen, although it should be noted that if the package contains many functions not all will be shown, as is the case with the ggplot2 package:

> ggplot2::

ggplot2::scale_fill_brewer         ggplot2::scale_size
ggplot2::GeomLine                  ggplot2::ScaleContinuousIdentity
ggplot2::geom_boxplot              ggplot2::guide_legend
ggplot2::ScaleDiscreteIdentity     ggplot2::Layout
ggplot2::scale_colour_ordinal      ggplot2::geom_hex
ggplot2::GeomRasterAnn             ggplot2::panel_cols
ggplot2::scale_colour_date         ggplot2::StatYdensity
ggplot2::stat_bin_2d               ggplot2::scale_y_sqrt
ggplot2::aes_all                   ggplot2::alpha
ggplot2::scale_shape               ggplot2::position_dodge2
[...truncated]

View the source code of R package functions

Sometimes it can be interesting to inspect the code of any function. For that purpose, you have several options:

  • Call the name of the function in console.
  • Press Ctrl + Left Click or Cmd + Left Click in the function name (written on the script), when using RStudio.
  • Go to the CRAN (or GitHub, R-forge, 
) page of the package and download the package file to inspect the source code manually.

Note that, if the function is written in Fortran, C or any different language than R, you won’t be able to see the code with the first and the second method.

library() vs require()

Both functions load a package, but they behave differently when the package is not installed. library stops with an error:

library(tidymodels)
Error in library(tidymodels) : there is no package called 'tidymodels'

On the other hand, require only throws a warning and returns FALSE, so the code keeps running:

require(tidymodels)
Loading required package: tidymodels
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called 'tidymodels'

Use library in your scripts, as it is better to get an error at the beginning than a different error later.

Check for installed packages

Sometimes you don’t remember if you have a package installed and you don’t want to waste your time reinstalling it. In order to avoid this, you can use the require function. Note that the main difference between require and library is that the first one returns a boolean and the second one returns an error if the package is not installed. The require function is designed to be used inside other functions.

# If FALSE, install the package
if (!require("ggplot2")) install.packages("ggplot2")

The following line of code will also return TRUE if the package is installed, or FALSE if not.

"ggplot2" %in% rownames(installed.packages())
[1] TRUE

However, the recommended way to check whether a package is installed is the requireNamespace function, as it is faster than installed.packages and it doesn’t attach the package to your session.

requireNamespace("ggplot2", quietly = TRUE)
[1] TRUE

Install packages only if they are missing

If you share your code, you can install only the packages that are not installed yet. Check each package with requireNamespace and pass the missing ones to install.packages:

pkgs <- c("ggplot2", "dplyr", "tidymodels")

installed <- vapply(pkgs, requireNamespace, logical(1), quietly = TRUE)
installed

missing <- pkgs[!installed]
missing
   ggplot2      dplyr tidymodels
      TRUE       TRUE      FALSE
[1] "tidymodels"
if (length(missing) > 0) install.packages(missing)

The pak::pkg_install function also skips the packages that are already installed and up to date.

Common errors when installing packages

Error: there is no package called ‘x’

This error appears when you try to load a package that is not installed (or not installed in the libraries listed by .libPaths()).

library(ggplot3)
Error in library(ggplot3) : there is no package called 'ggplot3'

Fix: check the spelling (package names are case-sensitive) and install the package with install.packages("package_name") before loading it. If you have just updated R, you will need to reinstall your packages.

Warning: package ‘x’ is not available for this version of R

You will see this warning when install.packages can’t find the package in the repository.

install.packages("ggplot3")
Warning message:
package 'ggplot3' is not available for this version of R

A version of this package for your version of R might be available elsewhere,
see the ideas at
https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages

Despite the message, the R version is often not the problem. The most common causes are:

  • The name is misspelled, for instance install.packages("GGplot2").
  • The package is not on CRAN: it is on Bioconductor (use BiocManager::install) or GitHub (use remotes::install_github).
  • The package was archived (removed from CRAN). Install an older version with remotes::install_version.
  • The package requires a newer R version. Check your R version and update R if needed.
  • Your repository or internet connection doesn’t work. Try setting a CRAN mirror with install.packages("pkg", repos = "https://cloud.r-project.org").

Warning: installation of package had non-zero exit status

This warning means that the installation failed and the package was not installed. The message looks like this:

# Warning message:
# In install.packages("package_name") :
#   installation of package 'package_name' had non-zero exit status

The real reason is printed above this message, so scroll up in the console. Usually:

  • The package must be compiled from source and you don’t have the compilers. Install Rtools on Windows, Xcode command line tools on macOS (xcode-select --install) or r-base-dev on Linux.
  • A system library is missing (on Linux, the message tells you which one, like libcurl or libxml2).
  • A dependency failed to install. Install it first on its own.
  • When R asks “Do you want to install from sources the package which needs compilation?”, answer no to install the binary version.

Error: Cannot remove prior installation of package

If you encountered this error, you might be using different versions of R in the same computer. The solutions are:

  • Close all open R sessions, open R again and install the package.
  • If it didn’t work, look at the error and go to the path where the 00LOCK file is and delete it.
  • Other option is to use the .libPaths() function, that returns the path where the libraries are, and delete the problematic package.

A similar problem appears when a previous installation was interrupted and left a lock folder behind:

# ERROR: failed to lock directory 'C:/Users/.../R/win-library/4.3' for modifying
# Try removing 'C:/Users/.../R/win-library/4.3/00LOCK-ggplot2'

Delete that 00LOCK folder manually or with unlink(), and install the package again. You can also skip the lock with install.packages("ggplot2", INSTALL_opts = "--no-lock").

Finally, if R says that the library is not writable (or you get cannot open file 
 Permission denied), you don’t have permissions on that folder. Accept to use a personal library when R asks for it, or run R as administrator.

Are you unable to install packages in R?

If you can’t install any package, there are many possible reasons:

  • You are disconnected from the internet.
  • The package is no longer available. Look for old versions with https://cran.r-project.org/src/contrib/Archive/Package_Name.
  • The name of the package is misspelled. Package names are case-sensitive.
  • Rtools is required to build the package, so you will need to have it installed.

If nothing works, try to close and open R again or try in another computer to verify if the problem persists.