在 x 是字符串的库中使用 eval(x) 时出错

Error when using eval(x) inside library where x is a string

我正在尝试了解 tidyeval。为什么会出现以下错误?

x <- "dplyr"
library(eval(x))
## Error in library(eval(x)) : 'package' must be of length 1

我们需要 character.only 选项作为 library 中的 TRUE,默认为 FALSE

library(x, character.only = TRUE)

character.only - a logical indicating whether package or help can be assumed to be character strings.

-在新的 R 会话中进行测试

> x <- "dplyr"
> library(x, character.only = TRUE)

Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

关于错误,它发生在以下步骤(如果我们调试函数),即当 character.onlyFALSE 时,它对代码执行 substitute (默认情况下) 并且这导致在将其转换为 character (as.character)

时创建长度为 2 的向量
> debugonce(library)
...

browse[2]> 
debug: lib.loc <- lib.loc[dir.exists(lib.loc)]
Browse[2]> 
debug: if (!character.only) package <- as.character(substitute(package))
Browse[2]> 
debug: package <- as.character(substitute(package))
Browse[2]> 
debug: if (length(package) != 1L) stop("'package' must be of length 1")
Browse[2]> 
debug: stop("'package' must be of length 1")
Browse[2]> 
Error in library(eval(x)) : 'package' must be of length 1

即在内部,代码执行 substitute 并且输出为 length 2 here

as.character(substitute(eval(x)))
[1] "eval" "x"   

在检查时抛出错误