EthicsComputerCourses
Join training +91 90532 10052

Packages & CRAN

R Programming · Lesson 24 of 29 Advanced 8 min read Updated

Base R is powerful, but much of R's strength comes from packages: bundles of functions, data and documentation written by the R community. There are packages for reading Excel files, drawing maps, fitting machine learning models, building web dashboards and analysing gene data. Most are free and live on CRAN, the same network that distributes R itself.

In this lesson you will install and load packages, call a function without loading its package, deal with name clashes, keep packages up to date and make a project reproducible.

Packages you already have

R ships with a set of base and recommended packages. A few, such as stats, graphics, utils and datasets, are loaded automatically when R starts. That is why lm(), plot() and mtcars work without any setup:

RTry it yourself
packageVersion("stats")
"package:stats" %in% search()
stats::sd(c(3, 9, 4))
c("mtcars", "iris", "airquality") %in% ls("package:datasets")
Output
[1] ‘4.6.0’
[1] TRUE
[1] 3.21455
[1] TRUE TRUE TRUE
  • packageVersion() reports a package's version; base packages share R's version number.
  • search() lists the packages attached in this session.
  • stats::sd() uses the double colon: package name, ::, function name. It calls a function from a package without attaching the whole package.
  • ls("package:datasets") lists the practice data sets that come with R; here %in% confirms that three of them are there.

Installing and loading

Installing and loading are two separate steps:

  1. Install once per computer (and again after a major R upgrade): install.packages() downloads the package from CRAN and puts it in your library folder.
  2. Load in every session where you use it: library() attaches the package so its functions are available.
R
install.packages("readxl")             # once: download from CRAN
install.packages(c("dplyr", "ggplot2")) # several at once
library(readxl)                        # every session: attach it
marks <- read_excel("marks.xlsx")      # now its functions work

Package names go in quotes for install.packages() and are usually written without quotes in library(). On Windows and macOS, CRAN provides ready-built binary packages, so installation is quick. On Linux, packages are often built from source, which takes longer and may need system libraries; Posit Public Package Manager offers Linux binaries if you want speed.

In RStudio the Packages pane, and in Positron the Packages view, let you do the same with clicks. Put library() calls at the top of your script, so anyone reading it sees what it needs. Never put install.packages() inside a script you share: it reinstalls every time and can change versions under someone else's feet.

Trying to load a package that is not installed gives a clear error:

RTry it yourself
library(notarealpackage)
Output
Error in library(notarealpackage) : there is no package called ‘notarealpackage’

The fix is install.packages("notarealpackage") (with the real name, of course). A typo in the name causes the same message, so check the spelling and capital letters first.

Masking: when two packages share a name

When a newly loaded package has a function with the same name as one already attached, the new one masks the old one. R tells you when this happens. Loading dplyr, for example, prints:

Text
Attaching package: 'dplyr'

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

    filter, lag

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

    intersect, setdiff, setequal, union

After this, filter() means dplyr's filter(), not the time-series filter from stats. This is normal and usually what you want. If you need the other one, use the double colon: stats::filter(). Using pkg::fun() everywhere in your own functions makes it obvious which package each function comes from.

require() is an older cousin of library() that returns FALSE instead of stopping when a package is missing. Inside scripts, prefer library(), which fails loudly. To test whether a package is available without attaching it, use requireNamespace():

RTry it yourself
has_tools <- requireNamespace("tools", quietly = TRUE)
has_fake <- requireNamespace("notarealpackage", quietly = TRUE)
c(tools = has_tools, notarealpackage = has_fake)
Output
tools notarealpackage 
 TRUE           FALSE 

requireNamespace() returns its answer invisibly, so the example stores both answers and prints them together. A typical use is if (!requireNamespace("readxl", quietly = TRUE)) stop("Please install readxl") at the top of a script.

Finding good packages

  • CRAN Task Views (on the CRAN website) group packages by topic, such as econometrics, time series or spatial data, and are maintained by experts.
  • Each CRAN package has a page with its description, version, reference manual and vignettes: longer tutorials. In R, vignette(package = "dplyr") lists them once the package is installed.
  • Bioconductor is a separate repository for biology and genomics packages, installed with the BiocManager package.
  • Development versions often live on GitHub or on R-universe; install those only when you need a fix that is not on CRAN yet.

Prefer packages that are on CRAN, recently updated, well documented and widely used. Every package you add is code you trust.

Updating and removing

R
update.packages(ask = FALSE)     # update all installed CRAN packages
remove.packages("readxl")        # uninstall a package
installed.packages()[, "Version"] # see versions of everything installed

After installing a new R version (for example moving from 4.5 to 4.6), you usually need to reinstall your packages, because each R minor version has its own library folder.

Reproducible projects with renv

Packages change over time. A script that works today may break next year after an update. The renv package records the exact version of every package a project uses, so you, a classmate or a server can rebuild the same setup later:

R
install.packages("renv")
renv::init()       # start: give this project its own private package library
renv::snapshot()   # record the package versions in renv.lock
renv::restore()    # on another computer: install exactly those versions

Commit the renv.lock file with your code. Another popular tool, pak, installs packages quickly and reports clearly what it is doing: pak::pak("dplyr").

Common mistakes

  • "there is no package called...": the package is not installed, or the name is misspelled. Names are case-sensitive.
  • "could not find function...": the package is installed but not loaded. Add library() at the top, or use pkg::function().
  • Installing in every script run. Install once; load every session.
  • Surprised by masking. Read the attach message, and use pkg::function() when names clash.

Key points

  • Packages extend R; CRAN hosts thousands of them, organised in Task Views.
  • install.packages("name") installs once; library(name) loads it in each session.
  • pkg::function() calls a function without attaching its package and avoids masking problems.
  • update.packages() updates, remove.packages() uninstalls, packageVersion() reports versions.
  • renv records package versions so a project can be rebuilt exactly.

Exercise

Write the first lines of an analysis script that uses the packages readxl and dplyr: install them (as a one-time command you would run in the console, shown as a comment), load them, and print their versions. Then, in the browser, check whether the stats and graphics packages are attached and print the version of utils.

Show solution
R
# Run once in the console, not in the script:
# install.packages(c("readxl", "dplyr"))
library(readxl)
library(dplyr)
packageVersion("readxl")
packageVersion("dplyr")
RTry it yourself
c("package:stats", "package:graphics") %in% search()
packageVersion("utils")
Output
[1] TRUE TRUE
[1] ‘4.6.0’

The install line stays commented so the script does not reinstall packages every time it runs. Base packages such as stats, graphics and utils are attached automatically and share R's version number.

Quick Quiz

1. How often do you need to run install.packages("dplyr") on one computer?

2. What does stats::filter() do?

3. R says it could not find the function read_excel. What is the most likely fix?

4. What does renv::snapshot() record?

Learn R Programming with a mentor

Free lessons get you started. Our Data Science & Machine Learning training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call