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

Time:02-27

I am trying to understand tidyeval. Why does the below error occur?

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

CodePudding user response:

We need character.only option as TRUE in library which is by default FALSE

library(x, character.only = TRUE)

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

-testing on a fresh R session

> 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

Regarding the error, it occurs from the following step (if we debug the function) i.e. it does a substitute on the code when the character.only is FALSE (by default) and this results in creating a vector of length 2 when it is converted to character (as.character)

> 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

i.e. internally, the codes does substitute and the output is of length 2 here

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

which throws the error on the check

  • Related