Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

r - How can library() accept both quoted and unquoted strings

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

> ggplot2
Error: object 'ggplot2' not found

Thus, obviously ggplot2 is not an object. How can library() accepts an undefined variable without complaining about it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...