R Packages

R packages bundle reusable functions and data, and the install.packages()/library() workflow is how you add that functionality to your own scripts.

What a Package Is

A package is a shareable, organized collection of R functions — and sometimes example data — that solves a particular category of problem, such as ggplot2 for graphics or dplyr for data manipulation. Base R already ships with several packages, like stats and utils, loaded automatically every time R starts.

Installing a Package

install.packages() downloads a package from a repository such as CRAN and installs it onto your computer. You only need to run this once per package on a given machine, not every time you use the package.

Example

install.packages("dplyr")

Loading a Package into Your Session

Installing a package just puts it on disk — you still need to load it into your current R session with library() before you can call its functions. Unlike installing, this has to be done every time you start a fresh R session.

Example

library(dplyr)
filter(mtcars, mpg > 25)

Checking What's Installed and Loaded

installed.packages() lists every package available on your machine, while search() shows which packages are currently attached to your session. require() behaves like library() but returns FALSE instead of throwing an error if the package is missing, which is handy inside conditional checks.

  • install.packages("pkg") installs a package
  • library(pkg) loads it for use in the current session
  • requireNamespace("pkg") checks availability without loading it
  • update.packages() updates everything you have installed
  • remove.packages("pkg") uninstalls a package
Note: CRAN is the default repository, but packages can also come from GitHub (via devtools::install_github()) or Bioconductor for specialized bioinformatics tools — install.packages() alone only reaches CRAN.

Exercise: R Packages

What is the correct order of steps to use a package that isn't yet installed on your computer?