Let's say I have a data frame df
in R, a vector of column names cols
of df
of unknown length and a list l
of length length(cols)
whose elements are vectors l[[1]],l[[2]],...,l[[length(cols)]]
describing filter conditions for the columns. How can I define a function of cols
and l
that returns the filtered dataset? In other words I would like to define a function that looks somewhat like this:
library(dplyr)
dynaFilter <- function(cols, l){
df %>%
filter(cols[1] %in% l[[1]], cols[2] %in% l[[2]], ...)
}
and does the following:
df = data.frame(a = c("Hello", "Hi", "Bye"),
b = c("John", "Jack", "John"),
c = c("Mum", "Dad", "Dad"))
dynaFilter(c("a", "c"), list(c("Hi", "Bye"), c("Dad")))
# returns the same as
# df %>%
# filter(a %in% c("Hi", "Bye"), c %in% c("Dad"))
dynaFilter(c("a", "b", "c"), list(c("Hi", "Bye"), c("Jack") ,c("Dad")))
# returns the same as
# df %>%
# filter(a %in% c("Hi", "Bye"), b %in% c("Jack"), c %in% c("Dad"))