I'm trying to write function that will perform filtering based on some optional user variables to threshold the input data before plotting either the filtered or unfiltered data. In this example where data is data.frame with multiple columns including two of interest (var1 and var2):
example_func <- function(
data,
low_cutoff_var1 = NULL,
high_cutoff_var1 = NULL,
low_cutoff_var2 = NULL,
high_cutoff_var2 = NULL) {
...
}
Now as part of this function I would like to filter the input data using the cutoffs if the user supplies them before plotting the data (either filtered or unfiltered depending on user choices). The filtering step would be:
data_filtered <- data %>%
filter(var1 > low_cutoff_var1 &
var1 < high_cutoff_var1 &
var2 > low_cutoff_var2 &
var2 < high_cutoff_var2)
However, the issue is if one or more of the cutoffs is NULL then the filter doesn't work.
Now I know could do things step-by-step for each of the cutoffs one at a time. i.e.:
if (!is.null(x = low_cutoff_var1) {
data_filtered <- data %>%
filter(var1 > low_cutoff_var1)
}
if (!is.null(x = high_cutoff_var1) {
etc
However, that seems inelegant and there is probably better way to write this function. I feel like maybe filter_if is the right choice but I'm having trouble with the syntax of that and how to use in my specific case.
Any advice on easier way to accomplish what I'm trying to do would be great!
Thanks! Sam