ZetCode

R packages

last modified November 19, 2026

A package is a collection of functions, data sets, and documentation that extends R. The base installation already contains the stats, graphics, and utils packages, and thousands more are available from CRAN. Installing a package downloads it once, while attaching it makes its exported objects available in the current session. This article covers library, the :: operator, require, detach, the search path, and the functions that report which packages are installed and which versions they have. The examples use the packages installed in the tutorial image.

The examples need the tibble and stringr packages, which are not part of base R. Install them once with install.packages(c("tibble", "stringr")); the installing packages section of the introduction explains the details.

Attaching a package

library attaches a package to the search path, which is the list of environments that R consults when it looks up a name. search prints that list from the front, where the global environment sits, to the base package at the end. An attached package appears as an entry such as package:tibble.

attach-package.R
library(tibble)
cat("version:", as.character(packageVersion("tibble")), "\n")
cat("attached:", "package:tibble" %in% search(), "\n")
print(head(search(), 6))

The script attaches tibble 3.3.1 and confirms that package:tibble is now on the search path. The first six entries are the global environment, the attached package, and four of the packages that R attaches at startup. A lookup for tibble now finds the function in the package environment before it reaches the base environment. Attaching a package never copies its objects into the workspace.

$ Rscript attach-package.R
version: 3.3.1 
attached: TRUE 
[1] ".GlobalEnv"        "package:tibble"    "package:stats"    
[4] "package:graphics"  "package:grDevices" "package:utils"    

Calling objects with the namespace operator

The :: operator calls an exported object directly from a package namespace without attaching the package. This is the safest style in scripts and in code that other people will run, because the reader can see where every function comes from and the search path is left unchanged.

namespace.R
df <- tibble::tibble(x = 1:3, y = c("a", "b", "c"))
print(df)
cat("class:", class(df)[1], "\n")
cat("exported objects:", length(getNamespaceExports("tibble")), "\n")

tibble::tibble builds a tibble even though the package was not attached, and the class of the result is tbl_df. The call getNamespaceExports reports forty-six exported objects in this version. A namespace also contains internal objects, but :: refuses to reach them; ::: does, and it should be avoided in ordinary code because internals can change without notice.

$ Rscript namespace.R
# A tibble: 3 × 2
      x y    
  <int> <chr>
1     1 a    
2     2 b    
3     3 c    
class: tbl_df 
exported objects: 46 

Checking for a package

library stops with an error when the package is missing, which is the right behaviour in a script that cannot work without it. require returns TRUE or FALSE instead, so it can guard optional code. The character.only argument lets the package name come from a variable.

check-package.R
needed <- c("tibble", "dplyr", "nonexistentpkg")
for (pkg in needed) {
  available <- suppressPackageStartupMessages(
    require(pkg, character.only = TRUE, quietly = TRUE))
  cat(pkg, ":", available, "\n")
}

The first two packages are available and the invented name is not, so the loop prints TRUE, TRUE, and FALSE without stopping. The startup messages of dplyr are suppressed, but attaching it still masks filter and lag from the stats package and several set operations from base. For a pure availability check, requireNamespace is better because it loads the namespace without attaching anything.

$ Rscript check-package.R
tibble : TRUE 
dplyr : TRUE 
nonexistentpkg : FALSE 

Detaching a package

detach removes a package from the search path. With unload = TRUE it also unloads the namespace, which frees its memory and makes a later library call start from a clean state. Detaching does not uninstall anything; the package stays on disk.

detach-package.R
library(stringr)
before <- length(search())
detach("package:stringr", unload = TRUE)
after <- length(search())
cat("entries before:", before, "\n")
cat("entries after:", after, "\n")
cat("still attached:", "package:stringr" %in% search(), "\n")

Attaching stringr adds one entry to the search path, and detaching removes it again, so the count falls from ten to nine and package:stringr is no longer present. The same effect can be produced by starting a fresh R session, which is often the cleaner choice. If another attached package imports stringr, the unload step can fail, and R reports that the namespace cannot be unloaded.

$ Rscript detach-package.R
entries before: 10 
entries after: 9 
still attached: FALSE 

Finding an installed package

An installed package lives in one of the library directories reported by .libPaths. find.package returns the directory of a named package, and the DESCRIPTION file inside it records the metadata that CRAN and R use, including the package name, version, license, and dependencies.

locate.R
path <- find.package("tibble")
cat("package path:", path, "\n")
desc <- read.dcf(file.path(path, "DESCRIPTION"))
print(desc[, c("Package", "Version")])

The package sits in the site library at /usr/local/lib/R/site-library/tibble, and its description reports version 3.3.1. read.dcf reads the Debian control format used by the file and returns a matrix with one row. The same information is available through packageDescription, which returns a list-like object and does not require the file path.

$ Rscript locate.R
package path: /usr/local/lib/R/site-library/tibble 
 Package  Version 
"tibble"  "3.3.1" 

Reporting package versions

A script that depends on add-on packages should state the versions it was tested with. packageVersion returns a version object and as.character turns it into a string. The version of R itself comes from getRversion.

report.R
required <- c("tibble", "dplyr", "tidyr", "data.table", "stringr")
for (pkg in required) {
  version <- as.character(packageVersion(pkg))
  cat(sprintf("%-10s %s\n", pkg, version))
}
cat("R version:", as.character(getRversion()), "\n")

The report lists tibble 3.3.1, dplyr 1.2.1, tidyr 1.3.2, data.table 1.18.6.1, and stringr 1.6.0 on R 4.5.2. The sprintf format %-10s pads each package name to ten characters, so the versions line up in a column. This loop assumes that every package is installed; the require check from earlier can guard a version that is optional.

$ Rscript report.R
tibble     3.3.1
dplyr      1.2.1
tidyr      1.3.2
data.table 1.18.6.1
stringr    1.6.0
R version: 4.5.2 

Next steps

The tibbles article introduces the first package used here, the dplyr article covers the second, and the data.table article shows a package with a very different syntax. The stringr article is a further example of a package that replaces base functions with a consistent interface. The next article, reading and writing data, uses these packages to move results between R and the file system.

Source

R documentation: library and require

R documentation: search

R documentation: detach

R documentation: find.package

R documentation: packageVersion

Writing R extensions

In this article we have attached packages with library and read the search path it changes. We called exported objects with :: without attaching anything, checked for optional packages with require, and removed a package with detach. We located an installed package and read its description file, then reported the versions of several packages together with the version of R. The series continues with R reading and writing data.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.