Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Provide multiple filter conditions as arguments to custom function using `filter` in R

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading