daniellga
daniellga

Reputation: 1224

Ignore argument in filter function

I have a function and I would like for this function to ignore the conditions applied to filter when the respective argument is not called.

Example:

dataset <- data.frame(a = c(1,2,3), b = c(4,5,6))

topcm <- function(data, feat1, feat2) {
  data %>% filter(a == feat1 & b == feat2) }

topcm(dataset, 2, 5) #should return only the second line of dataset

topcm(dataset, feat2 = 5) #I want it to return the second line as well, but it will instead give an error. I want it to still be able to filter, ignoring the conditional that isn't specified as an argument.

I know I can apply some "if"s to check if the arguments exists and break or continue from there, but if there are lots of arguments, I would need to do it one by one. Is there a simple way to do it?

Upvotes: 0

Views: 514

Answers (2)

user2554330
user2554330

Reputation: 44788

You could do it using defaults on the variables. For example,

topcm <- function(data, feat1 = data$a, feat2 = data$b) {
  data %>% filter(a %in% feat1 & b %in% feat2) }

The idea is this: the default value of feat1 is the expression data$a, which will be a vector containing all the values in column a of whatever dataframe was passed as data.

If you don't specify a value for feat1, the default will be used, and a %in% feat1 will always be TRUE because a and feat1 will be the same thing.

If you do specify a value, the default will be ignored, and the test will only be TRUE for those values you pass in as feat1.

Upvotes: 1

akrun
akrun

Reputation: 886938

An easier option is to have ... as arguments and pass expression as argument. Otherwise, we may need to evaluate with is_missing maybe_missing and it can be messier when dealing with lots of arguments

topcm <- function(data, ...) {
   data %>%
       filter(...) 


  }

topcm(dataset, a==2, b ==5) 
topcm(dataset, b == 5) 

Upvotes: 0

Related Questions