0

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"))
guzbrush
  • 123
  • 11
  • I'm surprised that this seem to be exactly the same question I had answered a week ago. Is this part of some kind of assignment? – MrFlick Mar 08 '18 at 14:53
  • No, sorry, was just a case of not having searched enough (and with the right terminology) – guzbrush Mar 09 '18 at 09:20

0 Answers0