I am trying to write a custom R function that can take an arbitrary number of conditions on which to filter a data frame. I know a solution where I provide the columns to filter on as one vector and the condition to be met as another vector (see reprex below), but it becomes tedious as the number of conditions to filter on increases, as I have to add more lines of .data[[filter.column[N]]] to the function code. It also doesn’t let me change the logical operator to something else.
customFilter <- function(data, filter.column, filter.by, select.column) {
data %>%
filter(.data[[filter.column[1]]] == filter.by[1],
.data[[filter.column[2]]] == filter.by[2]) %>%
select(!!!select.column) %>%
pull()
}
customFilter(mtcars, c('mpg', 'cyl'), c(21, 6), 'wt'))
Is there a better way to do this?
>Solution :
https://dplyr.tidyverse.org/articles/programming.html#any-number-of-user-supplied-expressions
customFilter <- function(.data, select.column, ...) {
.data %>%
filter(...) %>%
pull( {{select.column}} )
}
customFilter(mtcars, 'wt', mpg == 21, cyl == 6)
customFilter(mtcars, 'wt', mpg > 25, hp < 80, disp > 75)