Great question!
Let's crack open the library()
function to see how it works.
enter library
into your interactive session to see the innards of the function.
The key parts of the function are from lines 186 to 197.
if (!missing(package)) {
if (is.null(lib.loc))
lib.loc <- .libPaths()
lib.loc <- lib.loc[file.info(lib.loc)$isdir %in% TRUE]
if (!character.only)
package <- as.character(substitute(package))
if (length(package) != 1L)
stop("'package' must be of length 1")
if (is.na(package) || (package == ""))
stop("invalid package name")
pkgname <- paste("package", package, sep = ":")
newpackage <- is.na(match(pkgname, search()))
The key lines are
if (!character.only)
package <- as.character(substitute(package))
This means that as long as you don't change the character.only
argument of library to TRUE
, R will convert your package name into a character string and search for that.
Let's test:
> library(ggplot2,character.only=TRUE)
outputs:
Error in library(ggplot2, character.only = TRUE) :
object 'ggplot2' not found
whereas
library("ggplot2",character.only=TRUE)
loads the package.
Basically, no matter what you give the library()
function as an argument for package
it will convert it into a characters unless you specify character.only to be TRUE
.
As Dason points out in the comments, a good use of the character.only
argument is in cases where you have the library names stored as objects themselves.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…