from Gemini
Setting up R on Ubuntu is a smooth process, but because the versions in the standard Ubuntu repositories can sometimes be outdated, the "best practice" involves adding the official CRAN (Comprehensive R Archive Network) repository to your system.
Here is the step-by-step guide to a professional setup.
1. Install Base R
To get the latest version of R, you should add the CRAN repository maintained by Michael Rutter.
-
Update your indices and install the helper package for managing repositories:
Bashsudo apt update -qq sudo apt install --no-install-recommends software-properties-common dirmngr -
Add the CRAN signing key to verify the packages:
Bashwget -qO- https://cloud.r-project.org/bin/linux/ubuntu/marutter_pubkey.asc | sudo tee /etc/apt/trusted.gpg.d/cran_ubuntu_key.asc -
Add the repository (this command automatically detects your Ubuntu version, e.g., Noble, Jammy, or Focal):
Bashsudo add-apt-repository "deb https://cloud.r-project.org/bin/linux/ubuntu $(lsb_release -cs)-cran40/" -
Install R:
Bashsudo apt update sudo apt install r-base
2. Install Development Tools
Many R packages (like those in the tidyverse) are written in C++ or Fortran and need to be compiled on your machine. Without these system dependencies, package installation will often fail.
Run this to install the essential compilers and headers:
sudo apt install build-essential libcurl4-gnutls-dev libxml2-dev libssl-dev
3. Install an IDE (Posit/RStudio)
While you can run R in the terminal by typing R, most developers use RStudio Desktop.
-
Go to the Posit Download Page.
-
Download the .deb file for your version of Ubuntu.
-
Install it using
apt(which handles dependencies better than double-clicking):Bashsudo apt install ./rstudio-xxxx-amd64.deb
4. The "Ubuntu Secret": RPPAs
If you find that installing R packages takes too long because they are compiling from source, you can use the c2d4u (CRAN to Debian for Ubuntu) repository. This provides pre-compiled binaries for thousands of R packages, making installation nearly instant.
sudo add-apt-repository ppa:marutter/c2d4u4.0+
Now, instead of running install.packages("ggplot2") inside R, you can run sudo apt install r-cran-ggplot2 in your terminal.
5. Verify the Installation
Open your terminal and type R. You should see the console launch with the version information.
To test your graphics and compiler setup, try running this inside R:
plot(mtcars$mpg, mtcars$wt)
If a window pops up with a scatter plot, you are officially ready to code.
Are you planning to use R primarily for local data analysis, or are you setting this up on a server for something like a Shiny web app?
