[1] "datasets" "utils" "grDevices" "graphics" "stats" "methods"
[1] "stats" "graphics" "grDevices" "utils" "datasets" "methods"
[7] "base"
Chapter 4: R Packages
Shih Chien University
2026-08-03
A package is a bundled set of related functions, help files, and data files — the unit in which R functionality is shared.
stats package collects statistical analysis functions.Two steps precede using any package:
Why insist on explicit loading instead of loading everything?
fit, with strange and unexpected results. Loading only what you need minimizes the risk.Three quick diagnostics:
[1] "datasets" "utils" "grDevices" "graphics" "stats" "methods"
[1] "stats" "graphics" "grDevices" "utils" "datasets" "methods"
[7] "base"
base is missing from the default list because it implements core language features and is always loaded.R ships with a curated set of packages. The first group implements the language and environment themselves:
| Package | Default | Purpose |
|---|---|---|
base |
✓ | Core language: arithmetic, I/O, programming support |
utils |
✓ | Utilities: package management, file I/O, editing |
methods |
✓ | Formal (S4) classes and methods |
stats |
✓ | Statistical tests, distributions, modeling tools |
graphics |
✓ | Base graphics functions |
grDevices |
✓ | Graphics devices for base and grid graphics |
datasets |
✓ | Famous example data sets |
grid |
Lower-level engine for sophisticated graphics | |
compiler |
Byte-code compiler for R | |
parallel |
Parallel computation, parallel RNG | |
tools |
Package-development tools | |
tcltk |
Tcl/Tk interface for platform-independent UIs | |
codetools |
Code-analysis tools |
The second group provides widely used statistical methods — for many analyses you never need anything else:
| Package | Purpose |
|---|---|
MASS |
Functions and data from Venables & Ripley’s Modern Applied Statistics with S — a trove of useful statistics |
cluster |
Clustering algorithms |
class |
Classification: nearest neighbors, SOMs, LVQ |
nnet |
Feed-forward neural networks, multinomial log-linear models |
rpart |
Recursive partitioning and regression trees |
survival |
Survival analysis |
nlme |
Linear and nonlinear mixed-effects models |
mgcv |
Generalized additive (mixed) models |
splines |
Regression splines |
boot |
Bootstrap resampling |
KernSmooth |
Kernel smoothing |
spatial |
Kriging, point-pattern analysis |
foreign |
Reading Stata, SAS, SPSS files |
lattice |
Trellis graphics — prettier than the defaults |
stats4 |
Statistics as S4 classes/methods |
library() CommandUse a function from an unloaded package and R refuses:
Load the package first, and all is well:
require(), takes slightly different arguments (and returns FALSE instead of an error when the package is missing) — see the help files.library() call in your script anyway, or the script will fail when run elsewhere.library() call to the console so you can copy it into your script.Thousands of packages live online; the two biggest sources:
R can install from arbitrary repositories, but in practice nearly all projects publish on CRAN (some books even distribute sample code and data there). The modern exception: development versions on GitHub — covered shortly.
R’s own GUI installs packages well but searches them poorly. Use the browser:
| Repository | URL |
|---|---|
| CRAN | https://cran.r-project.org/web/packages/ (authoritative list; use your local mirror) |
| Bioconductor | https://www.bioconductor.org/packages/release/BiocViews.html |
| R-Forge | https://r-forge.r-project.org/ |
A search engine works too: the book’s tip is to search for “R package” + the application name. Its example: searching “R package multivariate additive regression splines” surfaces the mda package with its mars function — though the author later found the earth package a better choice for that algorithm. (Today, sites like https://r-universe.dev and CRAN Task Views make this search far easier.)
Installing through the Windows GUI:
Permissions matter here exactly as in Chapter 1: an Administrator account installs anywhere; a standard account may need R installed in its own directory, or R run as Administrator, to add packages.
The macOS installer interface shows more information but is a bit more confusing:
Two cautions from the book: R installs system-wide by default (choose an alternative location if you lack permissions), and this interface does not install dependencies automatically — loading a package whose dependencies are missing yields an error.
The console route works everywhere — and is the one to put in scripts. The book’s example, installing tree and maptree in one call:
R reports the download of each package and stores them in the default library (the location named by .Library). To uninstall, name the packages and the library they went into:
Note
Modern install.packages() resolves and installs dependencies automatically — one of the quiet improvements since the book’s edition.
The full family of console commands:
| Command | Description |
|---|---|
installed.packages |
Matrix describing all installed packages |
available.packages |
All packages available on the repository |
old.packages |
Installed packages with newer versions available |
new.packages |
Available packages not yet installed |
download.packages |
Download packages to a local directory |
install.packages |
Install packages from the repository |
remove.packages |
Remove installed packages |
update.packages |
Update installed packages to latest versions |
setRepositories |
Set the list of package repositories |
update.packages() at the start of term keeps your toolbox current.
Downloaded a package file yourself? Install it without launching the R shell, via R CMD INSTALL. The book’s example with aplpack (“Another PLotting PACKage”):
A successful run reports:
* Installing to library '/Library/Frameworks/R.framework/Resources/library'
* Installing *binary* package 'aplpack' ...
* DONE (aplpack)
Not everything lives on CRAN. The devtools package installs from git repositories and other URLs — the book’s example is the development version of ggplot2, which Hadley Wickham hosts on GitHub:
(The book’s call was install_github("ggplot2"); the function now requires the owner/repo form. The lighter-weight remotes package provides the same install_github() today.)
Building a package is the right move when you want to share code or data with others — or simply to pack your own work into a reusable, documented form. The book practices what it preaches: its data sets ship as the nutshell package, created exactly this way.
The easy path has three stops: create the directory skeleton, edit the metadata, build and check.
package.skeletonpackage.skeleton lays out the required directory structure and can copy a set of R objects into it:
| Argument | Description | Default |
|---|---|---|
name |
Name for the new package | "anRpackage" (the book: possibly the least useful default in all of R) |
list |
Names of R objects to include | |
environment |
Where to evaluate list |
.GlobalEnv |
path |
Filesystem location | "." |
force |
Overwrite an existing directory? | FALSE |
code_files |
Paths of files containing R code | character() |
The book’s own invocation:
R reports creating directories, a DESCRIPTION file, a Read-and-delete-me, saved functions and data, and help files. The key directories:
man/ — help files;R/ — R source files;data/ — data files, in any of three forms: R data files (save() output, suffix .rda/.Rdata), comma-separated .csv files, or R source .R files;DESCRIPTION — the package’s metadata, at the root.The generated template — every line meant to be edited:
Package: nutshell
Type: Package
Title: What the package does (short line)
Version: 1.0
Date: 2012-03-13
Author: Who wrote it
Maintainer: Whom to complain to <yourfault@somewhere.net>
Description: More about what it does (maybe more than one line)
License: What license is it under?
Useful optional fields:
LazyData — if yes, datasets load as lightweight promises rather than into memory (without it, call data() first); full access, (almost) no space.LazyLoad — the historical analogue for R code; ignored since R 2.14 (code is always lazy-loaded now).Depends — requirements on R or other packages, e.g. Depends: R(>= 2.8), nnet.R automates much of the help-file boilerplate with the prompt family:
prompt — generic documentation for an object;promptData — for data files;promptMethods — for methods of a generic function;promptClass — for a class.Each writes a skeleton .Rd file into man/ for you to complete. See their help pages for details. (Most modern developers generate .Rd files from inline comments with the roxygen2 package instead.)
With all materials in place, finish from the system command line (not the R shell). First verify the package complies with the rules and builds correctly:
Then build it:
Both accept --help for options. The definitive reference for serious package authors is the CRAN manual Writing R Extensions: https://cran.r-project.org/doc/manuals/R-exts.pdf.
Copyright. These slides are adapted from R in a Nutshell: A Desktop Quick Reference (2nd ed.) by Joseph Adler, O’Reilly Media. All rights reserved by the original author and publisher.
Non-commercial use only. These materials are strictly for educational purposes and may not be used for commercial gain.
Attribution. Any reproduction, distribution, or use of these materials must properly credit the original source.
R in a Nutshell: A Desktop Quick Reference