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 attachhelpโ optionally summon a help page for the packageposโ the position on the search list, given bysearch()lib.locโ the location of the R library tree to search through, orNULLcharacter.onlyโ whether the package argument is a character vectorlogical.returnโ ifTRUE, returnsTRUE/FALSEindicating success or failurewarn.conflictsโ warns when there are name conflicts (defaultTRUE)verboseโ triggers additional diagnostic messagesquietlyโ ifTRUE, 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.
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.