How can I utilize the magic dots (...) / ellipsis in order to filter based off an arbitrary column?
df = tibble::tibble(col1 = c('a', 'b', 'c'), col2 = c(1,3,4))
my_func = function(x, ...){
df %>%
dplyr::filter(... == x)
}
my_func('a', col1)
# Should return:
# A tibble: 1 x 2
col1 col2
<chr> <dbl>
1 a 1
We can convert to a quosure (quo
) and evaluate (!!
). Here, we assume there would be only a single column passed into the filter
my_func <- function(x, ...){
df %>%
dplyr::filter(!! quo(...) == x)
}
my_func('a', col1)
# A tibble: 1 x 2
# col1 col2
# <chr> <dbl>
#1 a 1
If there are multiple columns, then it may be better to use filter_at
It may be also better to make use of {{}}
if we can pass as an argument instead of ...
my_func <- function(x, coln) {
df %>%
filter({{coln}} == x)
}
my_func('a', col1)