简体   繁体   中英

Filter argument in function that defaults to make dplyr::filter() filter nothing

I am building a function that imports excel spreadsheets.

I would like the function to include an argument that contains names of variables that the user is interested in seeing. The values from the argument is used in dplyr::filter() inside the function. I would like the default value of the argument to include everything (ie not filter anything away).

Libraries and Data:

library(tidyverse)
data("iris")

The filter function without any default filter values (this works):

FILTER <- function(data = iris,
                   Filter_Values) {
  data %>%
    filter(Species %in% Filter_Values)
}
FILTER(Filter_Values = c("setosa", "virginica"))

As written above, I would like the Filter_Values argument to default into NOT filtering anything.
This works, but is of course not general:

FILTER <-
  function(data = iris,
           Filter_Values = c("setosa", "versicolor", "virginica")) {
    data %>%
      filter(Species %in% Filter_Values)
  }

FILTER()

Can you help me find a general term that can do the same. I have tried (and failed) with:

 Filter_Values = TRUE  
 Filter_Values = c(TRUE)   
 Filter_Values = regex(".*")
 Filter_Values = everything()

Any help appreciated,
Thanks

How about this?

FILTER <-
  function(data = iris,
           Filter_Values = unique(data$Species)) {
    data %>%
      filter(Species %in% Filter_Values)
  }

FILTER()

Perhaps:

FILTER <- function(data = iris,Filter_Values = NULL) {
    if (missing(Filter_Values)) data
    else data %>% filter(Species %in% Filter_Values)
}

FILTER()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM