R is a programming language for statistical analysis, data visualization, and graphics widely used by data scientists, statisticians, and researchers. Installing R on Ubuntu takes just a few minutes using the official CRAN repository, which ensures you always have access to the latest stable release.
This guide shows you how to add the CRAN repository to Ubuntu, install R core with development tools, and manage packages from the Comprehensive R Archive Network (CRAN). You will learn repository configuration, package management strategies, and troubleshooting techniques to keep your R environment current.
Choose Your R Installation Method
Ubuntu users can choose between three installation approaches: follow the official CRAN repository, lean on the r2u binary mirror for thousands of pre-built packages, or compile R from source when custom flags are required. Before diving into the commands, carefully pick the option that matches your support expectations and maintenance budget.
| Method | Version / Channel | Stability | Best For |
|---|---|---|---|
| CRAN APT Repository | Latest upstream R release for supported Ubuntu LTS versions | Fully tested, signed packages directly from CRAN maintainers | Default choice for most desktops and servers that need predictable updates |
| r2u (CRAN-Apt) | Daily-built CRAN and BioConductor packages as Debian binaries | High velocity with automatic dependency resolution through apt | Data science teams that need thousands of CRAN packages without compiling from source |
| Manual Source Build | Any tag from R sources with your own compiler flags | Depends on your toolchain, testing, and rebuild discipline | Power users who require patched builds, experimental features, or custom optimization |
Import CRAN APT Repository
Refresh Package Indexes and Update Installed Software
Before installing R on Ubuntu, first update your system to ensure all existing packages are current. Open your terminal (press Ctrl+Alt+T) and execute:
sudo apt update && sudo apt upgrade
Install HTTPS Transport and Repository Tools
Next, install the helper packages that provide HTTPS support, embedded key management, and the add-apt-repository utility. These tools enable secure repository access and GPG key verification:
sudo apt install --no-install-recommends ca-certificates curl gpg software-properties-common
Modern Ubuntu releases use the DEB822
.sourcesformat for repository configuration. The commands below create.sourcesentries that align with Ubuntu’s standard approach, even if older tools still emit legacy.listfiles.
Download CRAN Repository Signing Key
Download the signing key maintained by Michael Rutter directly into /usr/share/keyrings/ so APT can verify every package. Use curl to fetch the key securely:
sudo curl -fsSLo /usr/share/keyrings/cran.gpg https://cloud.r-project.org/bin/linux/ubuntu/marutter_pubkey.asc
The fingerprint of this key is E298 A3A8 25C0 D65D FD57 CBB6 5171 6619 E084 DAB9, matching the CRAN documentation. Next, verify the downloaded key fingerprint matches:
gpg --show-keys --with-fingerprint /usr/share/keyrings/cran.gpg
The output displays the key details you should verify against CRAN’s published fingerprint:
pub rsa2048 2010-10-19 [SCA] [expires: 2027-09-30]
E298 A3A8 25C0 D65D FD57 CBB6 5171 6619 E084 DAB9
uid Michael Rutter <marutter@gmail.com>
sub rsa2048 2010-10-19 [E] [expires: 2027-09-30]
Carefully compare the displayed fingerprint (E298 A3A8 25C0 D65D FD57 CBB6 5171 6619 E084 DAB9) against the published key ID on the CRAN Ubuntu repository page to confirm authenticity. The key should match Michael Rutter’s signing key, which CRAN uses for Ubuntu repository releases.
Adding the CRAN Repository
With the key saved, add a DEB822 .sources file that automatically tracks the CRAN mirror closest to you:
sudo tee /etc/apt/sources.list.d/cran.sources > /dev/null <<'EOF'
X-Repolib-Name: CRAN
Types: deb
URIs: https://cloud.r-project.org/bin/linux/ubuntu/
Suites: $(lsb_release -cs)-cran40/
Components: main
Architectures: $(dpkg --print-architecture)
Signed-By: /usr/share/keyrings/cran.gpg
EOF
The -cran40 suffix signals the ABI break introduced with R 4.0. Despite this suffix, CRAN still publishes the newest stable release for supported Ubuntu LTS versions, so you stay current without tracking version-specific commands.
Refresh Package Index
After adding the CRAN repository, refresh your package index so Ubuntu recognizes the new source:
sudo apt update
Finalize R Installation with Terminal Commands
Core R Installation
After adding the CRAN repository to your Ubuntu system, you can now install the base R metapackage, which brings the interpreter, standard library, and documentation:
sudo apt install r-base
Installing R Development Tools (Optional)
Additionally, power users who routinely compile CRAN packages from source should also install r-base-dev to pull in headers, compilers, and documentation:
sudo apt install r-base-dev
Verifying the R Installation
Confirm the installation by checking the R version and build information:
R --version
After running this command, the output displays the installed version along with platform and compiler details:
R version 4.5.0 (2024-04-24) -- "Shake and Throw" Copyright (C) 2024 The R Foundation for Statistical Computing Platform: x86_64-pc-linux-gnu R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications.
Managing Multiple R Versions (Optional)
By default, Ubuntu's CRAN repository installs R to /usr/bin/R and upgrades in place, replacing your existing version. However, if you need multiple R versions for testing package compatibility or reproducibility research, compile from source with a custom --prefix (for example --prefix=/opt/R/4.4.1) and create symlinks or shell aliases to switch between versions:
# Example: Install R 4.4.1 to /opt/R/4.4.1
./configure --prefix=/opt/R/4.4.1 --enable-R-shlib
make -j$(nproc)
sudo make install
# Create alias to access this version
echo "alias R-4.4.1='/opt/R/4.4.1/bin/R'" >> ~/.bashrc
source ~/.bashrc
This approach lets package maintainers test across R versions without affecting the system installation. Alternatively, use environment modules or Docker containers for more sophisticated version management in team environments.
Optional Development Libraries for Package Compilation
Install Recommended R Package Collection
r-recommended is a valuable package that includes a curated selection of R packages widely used in data analysis and statistical modeling. To install this collection, use the following command:
sudo apt install r-recommended
Installing SSL Support for CRAN Packages
For installing CRAN packages that require SSL encryption, such as the "httr" package, libssl-dev is necessary. Install this library with:
sudo apt install libssl-dev
Adding XML Parsing Capability
Similarly, to install CRAN packages needing XML parsing, libxml2-dev is required. This library is particularly crucial for packages like "XML". Install it using:
sudo apt install libxml2-dev
Enabling CURL Support in R
Finally, for CRAN packages that require CURL (Client URL) support, like the "curl" package, libcurl4-openssl-dev is essential. Use this command for installation:
sudo apt install libcurl4-openssl-dev
Overall, these development libraries let R packages build extensions for SSL connections, XML parsing, and HTTP requests - dependencies required by popular packages like httr, XML, and curl.
Understand R Package Management
Console Installation vs System Package Management
R packages can be installed two ways: from the R console using install.packages(), or system-wide through APT using r-cran-* packages. Console installation downloads packages into your home directory (~/.R/library/) and works for individual users without sudo privileges. In contrast, system packages install to /usr/lib/R/library/ and require sudo, making them available to all users on the system.
When to Use Each Method
Use console installation (install.packages()) for personal projects, testing packages, or when you need the latest CRAN release immediately. Alternatively, use APT packages (sudo apt install r-cran-*) for shared servers, reproducible deployments, or when you need Ubuntu's dependency tracking for system libraries like database connectors or SSL support.
CRAN vs r2u Binary Packages
The r2u project (covered later in this guide) bridges these approaches by converting CRAN packages into Ubuntu packages automatically. This gives you the latest CRAN versions with APT's dependency management, eliminating compilation time for complex packages like tidyverse or rstan.
Install R Packages via CRAN
Launching the R Interpreter
With R installed on your Ubuntu system, you can now install R packages from the Comprehensive R Archive Network (CRAN). To start the R console, open your terminal and run:
R
This launches the R interactive console. For most users, this user-level approach is preferred. However, if you need to install packages system-wide, you can run sudo -i R, but this is only recommended for shared systems where all users need access to the same packages.
Running R with
sudo -i Relevates privileges and can pose risks if installing untrusted packages. For personal projects, useRas a regular user instead so your package library stays in your home directory.
Installing R Packages
Once inside the R environment, you can install packages using the install.packages() function. This function is the standard method for adding new packages to your R setup. For instance, to install the ggplot2 and tidyr packages, type in the R console:
install.packages(c("ggplot2", "tidyr"))
R will download the packages and their dependencies from CRAN, compile them if necessary, and install them to your library directory. This process may take several minutes depending on package complexity and your system performance.
Searching for CRAN Packages
To explore available packages in CRAN, utilize the available.packages() function. This function is particularly useful for discovering packages in specific fields. In the R console, type:
available.packages()
This returns a comprehensive list of all available packages and their descriptions, aiding in informed decision-making about which packages to install. Alternatively, you can also browse the CRAN website directly to search packages by category or topic.
Updating Installed R Packages
Keeping your R packages up-to-date is crucial for security and functionality. To update all installed packages, use the update.packages() function in the R console. Furthermore, to update without individual confirmations, type:
update.packages(ask = FALSE)
This command efficiently updates all your installed packages to their latest versions, bypassing the need for manual confirmation.
Removing R Packages
If you need to remove an installed R package, the remove.packages() function comes in handy. For example, to delete a specific package, such as dplyr, in the R console type:
remove.packages("dplyr")
Overall, this straightforward approach ensures that you can effectively manage your system's packages, keeping only those necessary for your work.
Manage System-Wide R Packages with r2u (CRAN-Apt)
The default CRAN repository provides R packages as source code that compiles locally when you run install.packages(). For workflows requiring hundreds of packages - like tidyverse, Bioconductor, or machine learning stacks - compilation takes hours and occasionally fails when system dependencies are missing. Fortunately, the r2u project solves this by prebuilding CRAN packages as Ubuntu binaries with automatic dependency resolution through APT.
For comparison, installing complex packages like tidyverse (90+ dependencies) takes 15-20 minutes compiling from source on a typical system, but completes in under 2 minutes with r2u prebuilt binaries. Consequently, this speedup becomes critical when deploying containers, setting up CI/CD pipelines, or onboarding new team members.
Add the r2u Binary Repository (.sources)
First, import the CRAN-Apt (r2u) signing key and verify its fingerprint. Then create a .sources file and refresh APT:
sudo curl -fsSLo /usr/share/keyrings/cranapt.gpg https://eddelbuettel.github.io/r2u/assets/dirk_eddelbuettel_key.asc
Confirm the key matches the published fingerprint (AE89 DB0E E10E 60C0 1100 A8F2 A148 9FE2 AB99 A21A) before trusting it:
gpg --show-keys --with-fingerprint /usr/share/keyrings/cranapt.gpg
With the key verified, add the r2u .sources file and refresh the package index:
sudo tee /etc/apt/sources.list.d/cranapt.sources > /dev/null <<'EOF'
X-Repolib-Name: CRAN-Apt Packages
Types: deb
URIs: https://r2u.stat.illinois.edu/ubuntu
Suites: $(lsb_release -cs)
Components: main
Architectures: $(dpkg --print-architecture)
Signed-By: /usr/share/keyrings/cranapt.gpg
EOF
sudo apt update
r2u publishes amd64 binaries for Ubuntu 24.04 (noble), 22.04 (jammy), and 20.04 (focal). Ubuntu 24.04 additionally receives arm64 builds, while focal remains available in archived mode. The repository syncs with CRAN daily, so package updates appear quickly.
Prioritize r2u Packages with apt Pinning (Optional)
Optionally, assigning a higher priority to the CRAN-Apt release prevents Ubuntu's older r-cran-* builds from overriding r2u packages:
sudo tee /etc/apt/preferences.d/99cranapt > /dev/null <<'EOF'
Package: *
Pin: release o=CRAN-Apt Project
Pin: release l=CRAN-Apt Packages
Pin-Priority: 700
EOF
Install Packages via apt or bspm
Once r2u is active, you can install complex stacks, such as tidyverse or rstan, without compiling:
sudo apt install r-cran-tidyverse
Additionally, to let install.packages() call APT automatically, enable the bspm helper package:
sudo apt install python3-{dbus,gi,apt}
sudo Rscript -e 'install.packages("bspm")'
RHOME=$(R RHOME)
echo "suppressMessages(bspm::enable())" | sudo tee -a ${RHOME}/etc/Rprofile.site
echo "options(bspm.version.check=FALSE)" | sudo tee -a ${RHOME}/etc/Rprofile.site
The bspm helper intercepts install.packages() and installs the matching Ubuntu package from r2u instead of compiling from CRAN source, keeping your package database perfectly aligned with R library paths.
Clean Up the Legacy c2d4u Launchpad PPA
The c2d4u Launchpad page now displays "CURRENTLY NOT UPDATED", and CRAN's Ubuntu README directs users to r2u for maintained binaries. Remove the dormant PPA to avoid stale packages and signature warnings.
To clean up the legacy PPA, detach it, delete any leftover files, and refresh APT:
sudo add-apt-repository --remove ppa:c2d4u.team/c2d4u4.0+
sudo rm -f /etc/apt/sources.list.d/c2d4u-team-ubuntu-c2d4u4_0_*.list /etc/apt/sources.list.d/c2d4u-team-ubuntu-c2d4u4_0_*.sources
sudo apt update
Need a refresher on cleaning up PPAs, keys, and leftover packages? Follow our in-depth guide on removing a PPA from Ubuntu.
Building R from Source (Advanced Users)
Building from source requires manual updates whenever new R versions are released. You must download, compile, and reinstall each version yourself - there are no automatic security updates through APT. Only choose this path if you genuinely need custom compiler flags or experimental features. For production systems or shared servers, use the CRAN repository or r2u binaries instead.
For advanced users who need the latest development features or require custom compilation flags, building R from source offers complete control over the installation. Essentially, this method compiles R directly on your system, allowing you to optimize for your hardware and include experimental features not yet available in stable releases. However, this approach requires manual maintenance and updates.
Installing Build Dependencies
Before compiling R, you must install compiler tools and development libraries. These tools include GCC, Fortran compilers, and essential development headers. Execute the following command to install all necessary build dependencies:
sudo apt install build-essential gcc gfortran libreadline-dev libx11-dev libxt-dev libpcre2-dev zlib1g-dev libbz2-dev liblzma-dev libcurl4-openssl-dev libssl-dev libjpeg-dev libpng-dev libtiff-dev libicu-dev libxml2-dev libblas-dev liblapack-dev
Downloading and Extracting R Source Code
First, visit the R source code repository to identify the latest stable release. Then, replace 4.5.0 in the commands below with the current version number shown on the download page:
cd /tmp
wget https://cran.r-project.org/src/base/R-4/R-4.5.0.tar.gz
tar xzf R-4.5.0.tar.gz
cd R-4.5.0
Configuring and Compiling
Inside the extracted directory, configure the build with optimization flags and then compile using multiple processor cores. This process may take 5-15 minutes depending on your hardware:
./configure --prefix=/usr/local --enable-R-shlib && make -j$(nproc)
Installing and Verifying
Once compilation completes successfully, install R system-wide and verify the installation:
sudo make install && R --version
Troubleshooting Common R Installation Issues
GPG Signature Verification Failed
If apt update reports signatures could not be verified, first confirm the GPG key downloaded correctly to /usr/share/keyrings/cran.gpg and matches the expected fingerprint (E298 A3A8 25C0 D65D FD57 CBB6 5171 6619 E084 DAB9). If verification fails, re-download the key if the file is corrupt or outdated:
sudo curl -fsSLo /usr/share/keyrings/cran.gpg https://cloud.r-project.org/bin/linux/ubuntu/marutter_pubkey.asc
gpg --show-keys --with-fingerprint /usr/share/keyrings/cran.gpg
Package Compilation Fails During install.packages()
When compiling from source, R packages often require system development libraries. Therefore, install r-base-dev for compiler tools, plus specific libraries as error messages indicate: libssl-dev for SSL support, libcurl4-openssl-dev for network packages, libxml2-dev for XML parsing. Alternatively, the r2u repository eliminates compilation entirely by providing prebuilt binaries.
sudo apt install r-base-dev libssl-dev libcurl4-openssl-dev libxml2-dev
Permission Denied When Installing Packages
If install.packages() fails with permission errors, you are likely running R as root (sudo R) but trying to install to a user library, or running as a regular user trying to write to /usr/lib/R/library/. To resolve this, run R without sudo for personal package installation, or use sudo -i R only when installing system-wide packages intentionally.
Repository Configuration Conflicts
Mixing the official CRAN repository with the now-deprecated c2d4u PPA causes version conflicts and signature warnings. To resolve this, remove the c2d4u PPA completely (see the "Clean Up the Legacy c2d4u Launchpad PPA" section above) and rely on the official CRAN repository or r2u for binary packages.
R Version Mismatch After Update
If R --version shows an older version than expected after installation, first check that /usr/bin/R points to the correct binary. Typically, when building from source with custom prefixes, your PATH may prioritize the system R over your compiled version. To diagnose this issue, verify which R binary is active:
which R
R --version
Conclusion
You now have R installed on Ubuntu with access to the complete CRAN package ecosystem. With the CRAN repository enabled and the r2u mirror available for thousands of prebuilt binaries, you can easily install, update, and manage R packages system-wide or within your user environment. Ultimately, choose your installation method based on your workflow: use the R console for interactive package management in personal projects, or lean on r2u and apt for reproducible deployments across shared or production systems.
Next Steps: R Development Environment
With R installed, you can now enhance your workflow with these complementary tools tailored for R development:
RStudio Desktop provides syntax highlighting, project management, and interactive debugging for R development. Download the latest version from the Posit website - it works seamlessly with your CRAN installation and supports R Markdown for reproducible research documents.
Version control becomes critical when collaborating on R projects or publishing reproducible research. Therefore, install Git on Ubuntu to track changes, manage branches, and integrate with GitHub or GitLab for sharing analysis scripts and package development.
Document rendering tools extend R's capabilities for generating professional reports. For R Markdown documents and Shiny applications, install Pandoc (sudo apt install pandoc) and LaTeX (sudo apt install texlive-full) for PDF rendering capabilities.
Useful Links
Below are some valuable links related to using R on an Ubuntu system:
- R Project Official Website: Visit the official R Project website for comprehensive information about R, its features, and the latest updates.
- R for Ubuntu: Access the dedicated page for installing R on Ubuntu, including binaries and installation instructions.
- R Project Help: Find various help resources for R, including mailing lists, documentation, and user guides.
- R FAQs: Browse the frequently asked questions to find answers to common queries about R.
- R Manuals: Access a collection of manuals covering different aspects of R, from primary usage to advanced programming.
- R Certification: Learn about certification programs for R to validate your skills and knowledge.
- R on Stack Overflow: Join the R community on Stack Overflow to ask questions, share solutions, and get help from other R users.