R is an open-source programming language and environment built for statistical computing and data visualization. It is maintained by the R Foundation for Statistical Computing and is widely used by statisticians, data scientists, and researchers for data analysis, machine learning, and producing publication-quality charts and graphs.
The R packages in the default Ubuntu repositories tend to be several minor versions behind the current stable release. This guide shows you how to install R on Ubuntu 18.04 using the official CRAN repository to get the latest stable version, and how to install and use R packages.
Prerequisites:
The Ubuntu default repositories carry an older version of R. Adding the official CRAN repository gives you access to the latest stable release.
Install the packages needed to add an HTTPS-based repository:
bashsudo apt install apt-transport-https software-properties-common
Import the CRAN GPG key so your system trusts packages from the repository:
bashsudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
Add the CRAN repository for Ubuntu 18.04 (Bionic):
bashsudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'
Update the package list and install r-base:
bashsudo apt updatesudo apt install r-base
Confirm R installed correctly by checking the version:
bashR --version
The output shows the R version, release date, and license information. If you see R version 3.5.x, the installation worked.
Install build tools for R packages. Many R packages include compiled C or Fortran code. The build-essential package provides the GCC compiler, make, and C library headers that these packages need to compile during installation:
bashsudo apt install build-essential
Skipping this step causes package installations to fail when a package has any compiled components. Install it now to avoid those errors later.
Open the R console as root so packages install globally and are available to all users on the system:
bashsudo -i R
R displays a startup message with the version and license details. The > prompt means it is ready for input.
Install the stringr package, which provides a clean and consistent set of string manipulation functions:
rinstall.packages("stringr")
Load the library into your session:
rlibrary(stringr)
Create a character vector to work with:
rtutorial <- c("How", "to", "Install", "R", "on", "Ubuntu", "18.04")
Use str_length to count the character length of each element:
rstr_length(tutorial)
Output:
[1] 3 2 7 1 2 6 5
Each number is the length of the corresponding word in the vector. To install any other package, run install.packages("package_name") from inside the R console. Browse the full catalog of available packages at the CRAN package index.
R is now installed on your Ubuntu 18.04 system. Visit the official R introduction guide to explore data structures, functions, and statistical methods. Leave a comment below if you run into any issues.