【发布时间】:2020-11-25 04:25:31
【问题描述】:
我的问题类似于this question,但我需要跨列应用更复杂的函数,但我不知道如何将 Lionel 建议的解决方案应用于具有范围动词(如 filter_at() 或 @)的自定义函数987654323@+across() 等价。好像没有引入“superstache”/{{{}}} 运算符。
这是我想做的一个非编程示例(不使用 NSE):
library(dplyr)
library(magrittr)
foo <- tibble(group = c(1,1,2,2,3,3),
a = c(1,1,0,1,2,2),
b = c(1,1,2,2,0,1))
foo %>%
group_by(group) %>%
filter_at(vars(a,b), any_vars(n_distinct(.) != 1)) %>%
ungroup
#> # A tibble: 4 x 3
#> group a b
#> <dbl> <dbl> <dbl>
#> 1 2 0 2
#> 2 2 1 2
#> 3 3 2 0
#> 4 3 2 1
我还没有找到与 filter+across() 等效的 filter_at 行,但由于新的(ish)tidyeval 函数早于 dplyr 1.0,我认为可以搁置这个问题。这是我尝试制作一个程序版本,其中过滤变量由用户提供,带有点:
my_function <- function(data, ..., by) {
dots <- enquos(..., .named = TRUE)
helperfunc <- function(arg) {
return(any_vars(n_distinct(arg) != length(arg)))
}
dots <- lapply(dots, function(dot) call("helperfunc", dot))
data %>%
group_by({{ by }}) %>%
filter(!!!dots) %>%
ungroup
}
foo %>%
my_function(a, b, group)
#> Error: Problem with `filter()` input `..1`.
#> x Input `..1` is named.
#> i This usually means that you've used `=` instead of `==`.
#> i Did you mean `a == helperfunc(a)`?
如果有一种方法可以在 filter_at 的 vars() 参数中插入 NSE 运算符,而不必进行所有这些额外的调用,我会很高兴(我假设这是 {{{}}} 函数会做吗?)
【问题讨论】:
标签: r dplyr rlang tidyeval non-standard-evaluation