Skip to the workspace
Pebellslearn by building
Introduction and Setup  ›  Lesson

Installing Packages from CRAN

Installing Packages 10 mininstall.packages() downloads a package into your library once per machine, while library() loads an installed package into the current session every time you start R.

r programming / Installing Packages from CRAN

Explore each scene at your own pace.

01 · The rule

The rule

Installing Packages from CRAN

install.packages() downloads a package into your library once per machine, while library() loads an installed package into the current session every time you start R.

Separate installing a package from loading it into the current session.

The garden's newsletter editor wants a proper bar chart, and everyone says "use ggplot2". But ggplot2 is not part of R. It is a package: a bundle of functions, documentation and sometimes data that someone else wrote and shared. Getting packages right comes down to two steps that beginners constantly mix up.

The rule

Install once per machine; load with library() every session.

Install copies a package from CRAN onto your computer, into a folder called your library. You do this once, or again later when you want an update.

install.packages("ggplot2")   # quotes needed; downloads from CRAN

CRAN, the same network that hosts R itself, holds over 20,000 packages, each of which has to pass CRAN's automated checks. install.packages() also fetches everything the package depends on.

Load makes an installed package's functions available in the current session. Every time R starts fresh, you load again.

library(ggplot2)   # quotes optional; run at the top of each script

Two more tools worth knowing:

  • pkg::fun() calls one function from an installed package without loading the whole package: dplyr::n_distinct(crop) counts the distinct crops without a library(dplyr) line. It also makes clear which package a function came from.
  • pak is a modern installer. After a one-off install.packages("pak"), pak::pak("ggplot2") installs packages and their dependencies in parallel, explains conflicts clearly, and can install from GitHub with pak::pak("owner/repo").

Where does everything live? .libPaths() shows your library folders, and update.packages() updates what is already installed.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.