Installing Packages from CRAN
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.
The shortcut
Think of a bookshelf. Installing buys the book and puts it on your shelf: once. library() takes it off the shelf and opens it on your desk: every time you sit down to work. Buying the same book every morning is a waste; reading without opening it is impossible.
Buy the book
At the console, run
install.packages("ggplot2")once. It downloads from a CRAN mirror.
The common mistake is leaving install.packages() inside a script that runs every day. It re-downloads each time and fails without internet. Install at the console; keep only library() in the script.
Drills
Answer fast — trust the rule.
Which line installs the readr package?
You installed readr yesterday. Today, in a new R session, what must you run before using it?
library(janitor) fails with "there is no package called 'janitor'". What fixes it?
What does the :: in dplyr::n_distinct(crop) do?
What does pak::pak("ggplot2") do?
Remember
- Install once per machine; load with
library()every session. - Shortcut: installing buys the book,
library()opens it;pkg::fun()borrows one page. - Trap:
install.packages()inside a daily script, or forgettinglibrary()after a restart.
