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 CRANCRAN, 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 scriptTwo 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 alibrary(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 withpak::pak("owner/repo").
Where does everything live? .libPaths() shows your library folders, and update.packages() updates what is already installed.