How can library() accept both quoted and unquoted strings

后端 未结 2 1234
自闭症患者
自闭症患者 2020-12-16 00:21

For example, in an R session, typing library(ggplot2) and library(\"ggplot2\") can both import the library ggplot2. However, if I type ggplot2 in t

相关标签:
2条回答
  • 2020-12-16 01:08

    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.

    0 讨论(0)
  • 2020-12-16 01:19

    This is how (from the source of library(), which is....long):

    package <- as.character(substitute(package))
    

    A simple way to test this yourself:

    foo <- function(x) as.character(substitute(x))
    > foo(a)
    [1] "a"
    > foo("b")
    [1] "b"
    
    0 讨论(0)
提交回复
热议问题