使用dplyr :: select通过sym和enquo选择列范围

mik*_*eck 0 r dplyr rlang

BLUP:是否可以使用sym/ enquo将列范围传递给dplyr::select

考虑以下带有A至E列的标题:

library(tibble)
library(dplyr)
set.seed(4)
d = as_tibble(setNames(as.list(rnorm(5)), LETTERS[1:5]))
d
## # A tibble: 1 x 5
##       A      B     C     D     E
##   <dbl>  <dbl> <dbl> <dbl> <dbl>
## 1 0.217 -0.542 0.891 0.596  1.64
Run Code Online (Sandbox Code Playgroud)

我可以使用列运算符选择列的范围:,例如

select(d, B:D)
## # A tibble: 1 x 3
##        B     C     D
##    <dbl> <dbl> <dbl>
## 1 -0.542 0.891 0.596
Run Code Online (Sandbox Code Playgroud)

我什至可以通过这个范围作为保证:

cols = quo(B:D)
select(d, !!cols)
# same result as above
Run Code Online (Sandbox Code Playgroud)

但是我不能将其作为符号传递:

cols = quo(B:D)
select(d, !!cols)
# same result as above
Run Code Online (Sandbox Code Playgroud)

当在例如R封装内部使用列范围选择时,这是有问题的。

在我的实际示例中,我选择了20-40列的多个范围,因此我想坚持使用:运算符,而不是写出多个20-40元素向量并使用enquos(我认为这会起作用,但是我还没有测试过)。

Dic*_*oyT 5

您正在尝试将非语法名称B:D作为符号传递-您想要的是一个表达式。您可以rlang::parse_expr用来将字符串转换为表达式:

cols <- rlang::parse_expr("B:D")

select(d, !!cols)
## A tibble: 1 x 3
#       B     C     D
#   <dbl> <dbl> <dbl>
#1 -0.542 0.891 0.596
Run Code Online (Sandbox Code Playgroud)