5

我的问题与此问题类似,但我需要跨列应用更复杂的函数,但我不知道如何将 Lionel 建议的解决方案应用于具有范围动词 likefilter_at()filter()+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_at行,但由于新的(ish)tidyeval 函数早于 dplyr 1.0,我认为可以搁置这个问题。这是我尝试制作一个程序版本,其中过滤变量由用户提供,带有点:filteracross()

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)`?

如果有一种方法可以在vars()参数中插入一个 NSE 运算符filter_at而不必进行所有这些额外的调用,我会很高兴(我假设这是一个{{{}}}函数会做的事情?)

4

3 回答 3

4

也许我误解了问题所在,但转发点的标准模式似乎在这里工作正常:

my_function <- function(data, ..., by) {
  data %>%
    group_by({{ by }}) %>%
    filter_at(vars(...), any_vars(n_distinct(.) != 1)) %>%
    ungroup
}

foo %>%
  my_function( a, b, by=group )     # works
于 2020-08-05T02:56:15.687 回答
4

这是一种across()用于实现此目的的方法,在vignette("colwise").

my_function <- function(data, vars, by) {
  
  data %>%
    group_by({{ by }}) %>%
    filter(n_distinct(across({{ vars }}, ~ .x)) != 1) %>%
    ungroup()
  
}
 
foo %>%
  my_function(c(a, b), by = group)

# 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
于 2020-08-05T03:22:10.363 回答
2

一个选项across

my_function <- function(data, by, ...) {
 
  dots <- enquos(..., .named = TRUE)
  nm1 <- purrr::map_chr(dots, rlang::as_label) 
     
     
  data %>%
    dplyr::group_by({{ by }}) %>%
    dplyr::mutate(across(nm1, ~ n_distinct(.) !=1, .names = "{col}_ind")) %>%
    dplyr::ungroup() %>% 
    dplyr::filter(dplyr::select(., ends_with('ind')) %>% purrr::reduce(`|`)) %>%
    dplyr::select(-ends_with('ind'))
    
    
}

my_function(foo, group, a, b)
# 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

foo %>%
   group_by(group) %>%
   filter(any(!across(c(a,b), ~ n_distinct(.) == 1)))
# A tibble: 4 x 3
# Groups:   group [2]
#  group     a     b
#  <dbl> <dbl> <dbl>
#1     2     0     2
#2     2     1     2
#3     3     2     0
#4     3     2     1
于 2020-08-05T03:12:14.160 回答