How to Install R on Ubuntu 20.04

Published on

3 min read

Install R on Ubuntu 20.04

R is an open-source programming language and free environment that specializes in statistical computing and graphical representation. It is mainly used by statisticians and data miners for developing statistical software and performing data analysis.

This article covers the steps required to install R on Ubuntu 20.04.

Prerequisites

Ensure that you have met the following prerequisites before continuing with this tutorial:

Installing R on Ubuntu

The R packages included in the default Ubuntu repositories are often outdated. We’ll install R from the CRAN repository.

To install R on Ubuntu 20.04, follow these steps:

  1. Install the dependencies necessary to add a new repository over HTTPS:

    sudo apt install dirmngr gnupg apt-transport-https ca-certificates software-properties-common
  2. Add the CRAN repository to your system sources’ list:

    sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu focal-cran40/'
  3. Install R by typing:

    sudo apt install r-base
  4. The installation may take a few minutes to complete. Once completed, verify it by printing the R version:

    R --version
    R version 4.0.1 (2020-06-06) -- "See Things Now"
    Copyright (C) 2020 The R Foundation for Statistical Computing
    Platform: x86_64-pc-linux-gnu (64-bit)
    ...

That’s it, R has been installed on your Ubuntu machine, and you can start using it.

Compiling R Packages

One of the main reasons why R is so popular is the vast array of packages available through the Comprehensive R Archive Network (CRAN).

To be able to compile R packages, you need to install the build-essential package:

sudo apt install build-essential

For demonstration purposes, we’ll install a package named stringr , which provides fast, correct implementations of common string manipulations.

When started as root the packages will be installed globally and available for all system users. If you start R without sudo , a personal library will be set up for your user.

Open the R console:

R
>

Install the stringr package by typing:

install.packages("stringr")

The installation will take some time and once complete, load the library with:

library(stringr)

Create a simple character vector named tutorial:

tutorial <- c("How", "to", "Install", "R", "on", "Ubuntu", "20.04")

Run the following function which prints the length of a string:

str_length(tutorial)
[1] 3 2 7 1 2 6 5

You can find more R packages at Available CRAN Packages By Name and install them with install.packages().

Instead of compiling the R packages, you can install them as Debian packages from the cran2deb4ubuntu repository.

Conclusion

We’ve shown you how to install R on Ubuntu 20.04 and compile R packages.

If you hit a problem or have feedback, leave a comment below.