Reputation: 1932
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 (i.e. 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
Upvotes: 2
Views: 1172
Reputation: 2210
Perhaps:
FILTER <- function(data = iris,Filter_Values = NULL) {
if (missing(Filter_Values)) data
else data %>% filter(Species %in% Filter_Values)
}
FILTER()
Upvotes: 1
Reputation: 1963
How about this?
FILTER <-
function(data = iris,
Filter_Values = unique(data$Species)) {
data %>%
filter(Species %in% Filter_Values)
}
FILTER()
Upvotes: 1