Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 39 ยท Getting Started

R Packages: Install, Load and Use

Learn what R packages are, how to install them from CRAN with install.packages(), load them with library(), call functions with ::, and manage updates.

Base R comes with plenty of functions, but most of what makes R powerful lives in packages. A package is a bundle of functions, sample data and documentation written by someone else (or by you) and shared so everyone can reuse it. Need to read Excel files, draw maps or fit a random forest? There is almost certainly a package.

This lesson covers where packages come from, how to install and load them, and how to avoid the classic pitfalls.

Where packages live

flowchart LR
    A["CRAN<br/>(official repository)"] -->|install.packages| B["Your library<br/>(folder on disk)"]
    B -->|library| C["Your R session<br/>(functions available)"]

Figure: install once to disk, load in every session.

  • CRAN hosts more than twenty thousand reviewed packages. It is the default source.
  • Bioconductor specializes in bioinformatics.
  • GitHub hosts development versions and experimental packages.
  • Your library is the folder on your computer where installed packages are stored.

The key idea: install once, load every time. Installing downloads the package to disk. Loading makes its functions available in the current R session.

Installing a package

Use install.packages() with the package name in quotes:

R
install.packages("dplyr")

R downloads the package and anything it depends on. This can take a minute. You only need to do it once per computer (and again after a major R upgrade, because libraries are tied to the R version).

Do not put install.packages() at the top of a shared script. It reinstalls every time and surprises other people. Run it by hand in the console, and keep only library() calls in the script.

RStudio also has a Packages pane with an Install button that does the same thing.

Loading a package

Use library() with the name without quotes:

R
library(dplyr)

After this call, the functions of dplyr such as filter() and mutate() work. If you forget to load, you get an error like could not find function "mutate". If you forget to install, library(dplyr) fails with there is no package called 'dplyr'.

Load all the packages your script needs at the top, so a reader sees the requirements immediately:

R
library(dplyr)
library(ggplot2)
library(readr)

Calling a function without loading: ::

You can use one function from a package without loading everything:

R
dplyr::filter(mtcars, cyl == 4)

package::function() is useful when you need a function only once, and it removes any doubt about where the function comes from. It matters in the next section.

Name clashes (masking)

Two packages can define functions with the same name. When you load dplyr, R prints a message like:

Text
Attaching package: 'dplyr'

The following objects are masked from 'package:stats':

    filter, lag

This means filter() now refers to dplyr's version, not the one from the stats package. The last package loaded wins. Use stats::filter() or dplyr::filter() to choose explicitly. Messages are not errors, but read them: they explain surprising behavior.

The tidyverse

The tidyverse is a family of packages designed to work together, sharing one style. Installing the umbrella package gets them all:

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

Loading it attaches the core packages you will use constantly in this course:

Package Purpose
ggplot2 Charts
dplyr Filtering, grouping, summarizing data
tidyr Reshaping and tidying data
readr Reading CSV and text files
tibble Modern data frames
stringr Working with text
forcats Working with factors
purrr Functional programming
lubridate Dates and times

Base R and the tidyverse overlap. This course teaches the base way first where it helps you understand R itself, then the tidyverse way that most modern R code uses.

Useful package commands

R
installed.packages()[, "Package"]   # list what you have
packageVersion("dplyr")             # which version?
update.packages()                   # update everything
remove.packages("dplyr")            # uninstall

Learn what a package offers with:

R
help(package = "dplyr")     # index of help pages
vignette(package = "dplyr") # long-form tutorials

Many packages include vignettes: friendly guides written by the authors. They are often the best place to start.

Built-in datasets

R ships with small practice datasets, so you can try ideas without importing anything. A few are mtcars (fuel and engine data for 32 cars), iris (flower measurements) and airquality. See the list with data(). You will use these in later lessons:

R
head(mtcars, 3)
#>                mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1

Choosing and trusting packages

Anyone can publish a package, so check a few signs before depending on one:

  • Is it on CRAN (reviewed and tested on several systems)?
  • Was it updated recently, and are issues answered?
  • Does it have documentation and a vignette?
  • Is it widely used? Search for tutorials and questions.

Fewer dependencies mean fewer problems later. For serious projects, the renv package records the exact package versions you used so results stay reproducible.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the usual difference between install.packages() and library()?

    Install once per computer; load with library() in every new session.
  2. 2. Which call is correct for installing dplyr?

    The package name is given as a string in quotes.
  3. 3. What does the message "the following objects are masked from package:stats: filter" mean?

    Later-loaded packages take priority. Use stats::filter() to reach the original.
  4. 4. What does dplyr::filter() do?

    The :: operator picks a function from a named package.

Summary

  • Packages extend R; CRAN is the main source.
  • Install once with install.packages("name"), load each session with library(name).
  • Use package::function() to be explicit and to resolve name clashes.
  • The tidyverse is a coherent set of packages for data work, used heavily in this course.
  • Built-in datasets such as mtcars and iris are perfect for practice.

Next: Getting Help and Working Efficiently