Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

tidyeval

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>

}
like image 245
Shantanu Avatar asked Sep 07 '17 02:09

Shantanu


1 Answers

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>
like image 196
Kevin Arseneau Avatar answered Oct 06 '22 00:10

Kevin Arseneau