Search code examples
rdplyrtidyeval

What is the tidyeval way of using dplyr::filter?


Call the function below using foo(c("b")). The outputs are shown inline.

What is the right way of writing df %>% filter(!!x > (!!x))?

I have included an example of using mutate in tidyeval style to contrast it with filter.

foo <- function(variables) {

  x <- rlang::sym(variables[[1]])

  print(x)
  #> b

  print(typeof(x))
  #> [1] "symbol"

  df <- data_frame(a = 1, b = 2)

  print(df %>% mutate(!!x := 100 + !!x))

  #> # A tibble: 1 x 2
  #>         a     b
  #>       <dbl> <dbl>
  #>   1     1   102  

  print(df %>% filter(!!x  > (!!x)))

  #> Error in !x : invalid argument type

  print(df %>% filter(magrittr::is_greater_than(!!x, !!x)))

  #> # A tibble: 0 x 2
  #> # ... with 2 variables: a <dbl>, b <dbl>

}

Solution

  • You are most of the way there except for a minor typo, the round brackets in your filter statement should be on the variable and not the value.

    print(df %>% filter((!!x) > !!x))
    
    #> # A tibble: 0 x 2
    #> # ... with 2 variables: a <dbl>, b <dbl>