首页 > 解决方案 > 将符号向量转换为“...”的输入

问题描述

我有一个 R 函数,我想将符号向量 ( c(a, b)) 转换为...(eg a, b) 的输入。

# create data
set.seed(1)
data <- dplyr::tibble(a = sample(1:5, size = 10, replace = TRUE),
                      b = sample(1:5, size = 10, replace = TRUE))

该函数应如下所示:

f <- function(category) {
  # trying to work out
}
f(category = c(a,b))

并给出结果:

data |>
  tidyr::expand(tidyr::nesting(a, b))

困难在于我的函数将输入作为符号向量提供,而rlang::nesting将输入作为....

如何从一种格式转换为另一种格式?或者我应该使用其他功能rlang::nesting吗?

标签: rlazy-evaluationevaluationrlangtidyeval

解决方案


提供一组变量的接口c()应该基于 tidyselect。最简单的方法是使用select().

首先进行选择然后拼接数据:

f <- function(data, category) {
  sel <- dplyr::select(data, {{ category }})
  tidyr::expand(data, tidyr::nesting(!!!sel))
}

f(data, category = c(a, b))
#> # A tibble: 8 × 2
#>       a     b
#>   <int> <int>
#> 1     1     2
#> 2     1     5
#> 3     2     2
#> 4     2     5
#> 5     3     1
#> 6     3     5
#> 7     4     5

因为您通过select()您获得所有 tidyselect 功能进行交互:

f(data, category = starts_with(c("a", "b")))

推荐阅读