Skip to content
AgileLogics
4 min read

Packages

Prerequisites: Functions

A package is a bundle of R functions, data, and documentation that someone has shared. Packages are how R does almost everything beyond the basics — and there are over 20,000 on CRAN.

Install once, load every session

install.packages("dplyr")   # download and install — once per computer
library(dplyr)              # load it — once per R session
  • install.packages() downloads the package from CRAN. You only do this once (and again to update it).
  • library() makes the package's functions available in the current session. Put library() calls at the top of your scripts.

RStudio's Packages pane lists installed packages and has an Install button.

Using a function without loading the package

package::function() calls one function directly:

tools::toTitleCase("the art of data science")
[1] "The Art of Data Science"

This also makes it clear where a function comes from, and avoids clashes when two packages have functions with the same name (for example, both dplyr and base R have a filter function).

The tidyverse

install.packages("tidyverse")
library(tidyverse)

Installing tidyverse installs a whole family of packages that work well together — dplyr, ggplot2, tidyr, readr, stringr, forcats, lubridate, purrr, and tibble — and library(tidyverse) loads the core ones. Level 2 is built around them.

Choosing packages

Prefer packages that are widely used, actively maintained, and well documented. Each package's CRAN page links to its reference manual and "vignettes" — long-form tutorials that are often the best way to learn it.

Common mistakes

  • Calling install.packages() inside a script that others run — it reinstalls every time. Keep installation separate from analysis.
  • there is no package called 'dplyr' — the package isn't installed yet.