library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 3.6.1
conditional_filter <- function(l_disp = NULL, u_disp = NULL, l_hp = NULL, u_hp = NULL) {
mtcars %>%
# tidy up mtcars
rownames_to_column() %>%
as_tibble() %>%
select(rowname, disp, hp) %>%
# only filter on arguments that are defined
when(!is_empty(l_disp) ~ filter(., disp > l_disp), TRUE ~ .) %>%
when(!is_empty(u_disp) ~ filter(., disp < u_disp), TRUE ~ .) %>%
when(!is_empty(l_hp) ~ filter(., hp > l_hp), TRUE ~ .) %>%
when(!is_empty(u_hp) ~ filter(., hp < u_hp), TRUE ~ .) %>%
str()
}
conditional_filter()
#> Classes 'tbl_df', 'tbl' and 'data.frame': 32 obs. of 3 variables:
#> $ rowname: chr "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Hornet 4 Drive" ...
#> $ disp : num 160 160 108 258 360 ...
#> $ hp : num 110 110 93 110 175 105 245 62 95 123 ...
conditional_filter(u_disp = 170)
#> Classes 'tbl_df', 'tbl' and 'data.frame': 16 obs. of 3 variables:
#> $ rowname: chr "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Merc 240D" ...
#> $ disp : num 160 160 108 147 141 ...
#> $ hp : num 110 110 93 62 95 123 123 66 52 65 ...
conditional_filter(u_disp = 170, l_hp = 120)
#> Classes 'tbl_df', 'tbl' and 'data.frame': 3 obs. of 3 variables:
#> $ rowname: chr "Merc 280" "Merc 280C" "Ferrari Dino"
#> $ disp : num 168 168 145
#> $ hp : num 123 123 175
Created on 2019-09-20 by the reprex package (v0.3.0)
Note:
!is_empty()
should probably be wrapped in parentheses—I think the formula operator~
is lower precedence, but this is dangerous...