我正在尝试添加在 dplyr 中使用动态数量的变量进行过滤的功能。我希望用户能够在函数调用中以简单的方式输入命令,即...- 下面的示例应该会有所帮助。用户应该能够通过简单地将它们输入到函数中来分割出来seg1 == 'b',但所有尝试都失败了。使用标准 SQL 很容易做到这一点,只是不熟悉 NSE 格式。seg2 == 'd'my_func(example_data, seg1 = 'b', seg2 = 'd')
library('tidyverse')
example_data = tibble(seg1 = c('a','b','b','c'),
seg2 = c('d', 'd', 'd', 'e'),
out = c(1, 10, 20, 40))
my_func = function(dat, ...){
args = list(...)
arg_names = names(args)
### ????
dat = dat %>%
filter(???)
### ????
return(dat)
}
my_func(example_data, seg1 = 'b', seg2 = 'd')
# Desired output
> example_data %>% filter(seg1 == 'b', seg2 == 'd')
# A tibble: 2 x 3
seg1 seg2 out
<chr> <chr> <dbl>
1 b d 10
2 b d 20
Run Code Online (Sandbox Code Playgroud)
不要让我解释这个,因为大部分rlang对我来说仍然是难以形容的迟钝。我通过随机尝试来解决这个问题。
my_func = function(dat, ...){
args <- rlang::enexprs(...)
dat %>%
filter(!!! args)
}
> my_func(example_data, seg1 == 'b', seg2 == 'd')
# A tibble: 2 x 3
seg1 seg2 out
<chr> <chr> <dbl>
1 b d 10
2 b d 20
Run Code Online (Sandbox Code Playgroud)
请注意 的使用==,因此我们将表达式传递给...,而不是命名参数。