Programming for Applications

Chapter 4: R Packages

Yu-You Liou (NTU)

Shih Chien University

2026-08-03

The Package System

What Is a Package?

A package is a bundled set of related functions, help files, and data files — the unit in which R functionality is shared.

  • Rough analogues elsewhere: modules in Perl, libraries in C/C++, classes in Java. (Careful, C programmers: in R, “library” means the place packages live, not the package itself.)
  • Typically the contents are thematically related: the stats package collects statistical analysis functions.
  • The ecosystem is enormous: graphics packages, statistical tests, cutting-edge machine learning — and industry-specific tools for microarray data, credit risk modeling, the social sciences…
  • Some packages ship with R; thousands more live in public repositories; and you can build your own. This chapter covers all three.

Libraries, and Why Packages Must Be Loaded

Two steps precede using any package:

  1. it must be installed into a local library (by default one system-level library; you can add more);
  2. it must be loaded into the current session.

Why insist on explicit loading instead of loading everything?

  • Help-system speed: every loaded package slows help searches (the book’s author learned this writing with dozens loaded).
  • Name conflicts: two packages may define objects with the same name — you could silently call the wrong fit, with strange and unexpected results. Loading only what you need minimizes the risk.

Listing Packages

What Is Loaded, What Is Available

Three quick diagnostics:

getOption("defaultPackages")   # loaded at startup (omits base, always loaded)
[1] "datasets"  "utils"     "grDevices" "graphics"  "stats"     "methods"  
(.packages())                  # currently loaded (note the outer parentheses)
[1] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
[7] "base"     
(.packages(all.available=TRUE))  # everything installed in your libraries
library()                        # same idea, shown in a window
  • base is missing from the default list because it implements core language features and is always loaded.

Included Packages (1): Infrastructure

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

Included Packages (2): Statistics and Modeling

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

Loading Packages

The library() Command

Use a function from an unloaded package and R refuses:

fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis)
Error in `rpart()`:
! 沒有這個函式 "rpart"

Load the package first, and all is well:

library(rpart)
  • A sibling command, require(), takes slightly different arguments (and returns FALSE instead of an error when the package is missing) — see the help files.
  • GUIs offer menu-driven loading too — but always put the library() call in your script anyway, or the script will fail when run elsewhere.

Loading via the GUI, per Platform

  • Windows / Linux GUI: choose Load package from the Packages menu; a window lists the packages available to load.
  • macOS: fancier — choose Package Manager from the Packages & Data menu. The Package Manager shows which packages are loaded, loads them with a click, and even browses each package’s help file.
  • RStudio users: the Packages pane does the same job with checkboxes — and writes the library() call to the console so you can copy it into your script.

Exploring Package Repositories

CRAN, Bioconductor, R-Forge

Thousands of packages live online; the two biggest sources:

  • CRAN (Comprehensive R Archive Network) — hosted by the R Foundation, mirrored worldwide (pick a nearby mirror: faster for you, kinder to the servers). The book counted 1,698 packages in February 2009; today the count exceeds 20,000. If you know Perl: CRAN is R’s CPAN.
  • Bioconductor — an open-source project for genomic-data analysis tools, built on R, distributed as R packages through its own channel (mostly not on CRAN).
  • R-Forge — collaborative development site for works in progress; interesting but read the disclaimers — many projects there are unfinished.

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.

Finding Packages on the Web

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 Packages

Windows and Linux GUIs

Installing through the Windows GUI:

  1. (Optional) By default R fetches from the “CRAN” and “CRAN (extra)” categories; pick more via Select repositories on the Packages menu.
  2. From the Packages menu, choose Install package(s).
  3. First install of the session? R asks you to pick a mirror — choose one nearby.
  4. Click the package you want and press OK; R downloads and installs it.

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.

macOS GUI

The macOS installer interface shows more information but is a bit more confusing:

  1. From the Packages & Data menu, select Package Installer.
  2. (Optional) A menu at the top-left selects the package category — initially “CRAN (binaries)”.
  3. Click Get List to display available packages.
  4. The search box filters the list — but only after you’ve clicked Get List.
  5. Select the packages you want and press Install Selected.

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.

Installing from the R Console

The console route works everywhere — and is the one to put in scripts. The book’s example, installing tree and maptree in one call:

install.packages(c("tree", "maptree"))

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:

remove.packages(c("tree", "maptree"), .Library)

Note

Modern install.packages() resolves and installs dependencies automatically — one of the quiet improvements since the book’s edition.

The Package-Management Vocabulary

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.

Installing from the System Command Line

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”):

$ R CMD INSTALL aplpack_1.1.1.tgz

A successful run reports:

* Installing to library '/Library/Frameworks/R.framework/Resources/library'
* Installing *binary* package 'aplpack' ...
* DONE (aplpack)

Installing from Other Repositories: devtools

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:

# first time only:
install.packages("devtools")

library(devtools)
install_github("tidyverse/ggplot2")   # modern repo path: owner/repo

(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.)

Custom Packages

Why Build Your Own?

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.

Creating a Package Directory: package.skeleton

package.skeleton lays out the required directory structure and can copy a set of R objects into it:

package.skeleton(name = "anRpackage", list, environment = .GlobalEnv,
                 path = ".", force = FALSE, code_files = character())
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()

What the Skeleton Contains

The book’s own invocation:

package.skeleton(name = "nutshell", path = "~/Documents/book/current/")

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 DESCRIPTION File

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.

Documenting the Package

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.)

Building and Checking

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:

$ R CMD check nutshell

Then build it:

$ R CMD build nutshell

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.