6  Installing Packages

R comes with a large set of functions and packages. A package is a collection of functions that have been designed for a specific purpose. One of the great advantages of R is that many analysts, scientists, programmers, and users can create their own packages and make them available so that everybody can use them. R packages can be shared in different ways. The most common way to share a package is to submit it to what is known as CRAN, the Comprehensive R Archive Network.

You can install a package using the install.packages() function. To do this, I recommend that you run this command directly on the console. In other words, do not include this command in a source file (e.g. R script file, Rmd file). The reason for running this command directly on the console is to avoid getting an error message when running code from a source file.

To use install.packages() just give it the name of a package, surrounded by quotes, and R will look for it in CRAN, and if it finds it, R will download it to your computer.

# installing (run this on the console!)
install.packages("knitr")

You can also install a bunch of packages at once by placing their names, each name separated by a comma, inside the c() function:

# run this command on the console!
install.packages(c("readr", "ggplot2"))

Once you installed a package, you can start using its functions by loading the package with the function library(). For better or worse, library() allows you to specify the name of the package with or without quotes. Unlike install.packages() you can only specify the name of one package in library()

# (this command can be included in an Rmd file)
library(knitr)      # without quotes
library("ggplot2")  # with quotes

By the way, you only need to install a package once. After a package has been installed in your computer, the only command that you need to invoke in order to use its functions is the library() function.


6.1 Exercises

1) On the console, use the function install.packages() to install the package "rvest"

Show answer
install.packages(c("rvest", "RColorBrewer", "bookdown"))


2) On the console, use the function install.packages() to install the packages "shiny" and "bookdown".

Show answer
install.packages(c("shiny", "bookdown"))


3) Refer to the pane that has the tabs Files, Plots, Packages. Click on the tab Packages, and then click on the button Install to install the package "RColorBrewer".


4) Refer to the pane that has the tabs Files, Plots, Packages. Click on the tab Packages. Inspect the list of installed packages in your computer and see if you have the following packages:

  • "base"
  • "cluster"
  • "grid"
  • "stats"