oscar1mn
oscar1mn

Reputation: 33

programming a filter in tidyverse using quoting

I have a tibble with paired variables:
- a_x, a_y,
- b_x, b_y,
- c_x, c_y and so on.

How can I write a function that filters depending on "a", "b" or "c". For instance I want to return

filter(df, a_x != a_y) 

or

filter(df, b_x != b_y)

I'm using quosures, as described in https://dplyr.tidyverse.org/articles/programming.html, but without success.

This is the example:

test <-tribble(~a_x, ~b_x, ~a_y, ~b_y,
1,2,1,2,
5,6,5,8,
9,8,11,8)

# that works
x <-quo(a_x)
y <-quo(a_y)
filter(test, !!x == !!y)
x <-quo(b_x)
y <-quo(b_y)
filter(test, !!x == !!y)

# but the function doesn't work
my <- function(df, var){
a <- paste0(quo_name(var), "_x")
b <- paste0(quo_name(var), "_y")
print(quo(filter(df, !!a == !!b)))
return(filter(df, !!a == !!b))
}
my(test, "a")
my(test, "b")

Upvotes: 3

Views: 328

Answers (1)

akrun
akrun

Reputation: 887691

As we are passing a string, it is easier to convert to symbol and evaluate

library(dplyr)
library(rlang)
my <- function(df, var){
 a <- sym(paste0(var, "_x"))
 b <- sym(paste0(var, "_y"))
 df %>% 
     filter(!!a == !!b)

} 


my(test, "a")
# A tibble: 2 x 4
#    a_x   b_x   a_y   b_y
#  <dbl> <dbl> <dbl> <dbl>
#1     1     2     1     2
#2     5     6     5     8
my(test, "b")
# A tibble: 2 x 4
#    a_x   b_x   a_y   b_y
#  <dbl> <dbl> <dbl> <dbl>
#1     1     2     1     2
#2     9     8    11     8

If the OP intends to pass unquoted arguments as well,

my <- function(df, var){
   a <- sym(paste0(quo_name(enquo(var)), "_x"))
   b <- sym(paste0(quo_name(enquo(var)), "_y"))

   df %>% 
      filter(!!a == !!b)
}

my(test, a)
my(test, b)

NOTE: The above takes both quoted and unquoted arguments

identical(my(test, "a"), my(test, a))
#[1] TRUE
identical(my(test, "b"), my(test, b))
#[1] TRUE

Upvotes: 3

Related Questions