r - 将符号向量转换为“...”的输入
问题描述
我有一个 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
吗?
解决方案
提供一组变量的接口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")))
推荐阅读
- javascript - 对地图中的数据进行字符串化?
- c++ - 语法“ContextRegistrar_##ContextType”的含义
- performance - Powershell 性能
- mysql - 如何获得总用户平均时间超过 7 天
- python - 如何将 Google Colab 连接到 Cassandra?
- laravel - Laravel @guest 无法识别自定义守卫之一
- r-markdown - 如何像使用 ioslides 一样获得便携式 Xarginan 演示文稿?
- laravel - Laravel 5.6 符号链接问题,404 Not Found,但路径确实存在
- android - java.lang.IllegalStateException:预期的 BEGIN_OBJECT
- java - 具有大量记录的休眠序列生成器