R's library() Function Dissected

Christopher Peters ยท R Internals

library(): possibly the most common function call in R. What does it do? This is a dissection of the prolific function. For reference, here's the full function source.

The Function Signature

function(package, help, pos = 2, lib.loc = NULL,
         character.only = FALSE, logical.return = FALSE,
         warn.conflicts = TRUE, quietly = FALSE,
         verbose = getOption("verbose"))

Arguments Explained

  • package โ€” the name of the library to attach
  • help โ€” optionally summon a help page for the package
  • pos โ€” the position on the search list, given by search()
  • lib.loc โ€” the location of the R library tree to search through, or NULL
  • character.only โ€” whether the package argument is a character vector
  • logical.return โ€” if TRUE, returns TRUE/FALSE indicating success or failure
  • warn.conflicts โ€” warns when there are name conflicts (default TRUE)
  • verbose โ€” triggers additional diagnostic messages
  • quietly โ€” if TRUE, suppress all printing and warnings

Internal Functions

The library() function relies on four internal functions: testRversion, checkLicense, checkNoGenerics, and checkConflicts. They're specified up front in the function body.

How Loading Works

After the internal functions are specified, library() begins with a check of the verbose and quietly arguments:

if (verbose && quietly)
  message("'verbose' and 'quietly' are both true; being verbose then ..")

Next, if lib.loc is NULL (default), it's obtained by .libPaths():

if (!missing(package)) {
  if (is.null(lib.loc))
    lib.loc <- .libPaths()

.libPaths()
## [1] "/Users/statwonk/Library/R/3.2/library"
## [2] "/Library/Frameworks/R.framework/.../library"

Then a quick check that the paths exist โ€” .libPaths() might return a non-existent path:

lib.loc <- lib.loc[dir.exists(lib.loc)]

Quoted vs Unquoted Package Names

library() can be used as library("survival") or without quotes as library(survival). When character.only is FALSE (the default), the substitute function captures the expression and converts it to a character vector.

Key Takeaway: Every library() call walks through path resolution, version checking, license validation, namespace loading, and conflict detection โ€” a deceptively rich function behind R's most common one-liner.
Discuss an R Development Project