library() and Packages (R)

A package is a bundle of R functions, data, and documentation. You install one once with install.packages() and load it into a session with library() to use its functions.

R

R's power comes from its thousands of packages. The two-step workflow is: install.packages("dplyr") downloads and installs a package from CRAN (done once per machine), and library(dplyr) loads it into the current R session so its functions become available (done every session). require() is a softer variant that returns FALSE instead of erroring if the package is missing.

Once loaded, you call a package's functions directly. To call a single function without loading the whole package — or to disambiguate when two packages export the same name — use the pkg::function form, e.g. dplyr::filter(). This explicit form also documents which package a function comes from.

Packages live on repositories: CRAN is the main official one, Bioconductor serves bioinformatics, and many in-development packages live on GitHub (installed with remotes/devtools). The tidyverse is a meta-package that loads a whole family at once with library(tidyverse).

Syntax

install.packages("ggplot2")   # once
library(ggplot2)              # each session

Examples

R — library() loads a package; pkg::fn calls a function directly.

library(stats)
x <- c(4, 8, 15, 16, 23, 42)
print(median(x))
print(stats::sd(x))

Learn it in a lesson

See also

Back to the Dictionary