If we have to filter a dataframe we use the following based on variable name and its values
library(dplyr)
mtcars %>% filter(gear == 3)
# or
mtcars %>% filter(gear == 3 & carb == 3)
# or
mtcars %>% filter(gear == 3 & carb == 3 & cyl == 8)
Instead of updating the code repeatedly What I want is dynamically filter the dataframes on the fly. Something like below
choice <- c(gear == 3 & carb == 3 & cyl == 8)
mtcars %>% filter(choice)
I can select whatever variables I want to filter in the beginning and assign it to a variable and then simply pass that variable to filter function
The analogy to it is the following which is doing group by
choice <- c("gear", "carb", "cyl")
mtcars %>%
group_by_at(vars(one_of(choice))) %>%
summarize(Average=mean(mpg))
Is it doable in R?
CodePudding user response:
You may use an expression
and eval
uate it.
choice <- expression(gear == 3 & carb == 3 & cyl == 8)
mtcars |> subset(eval(choice))
# mpg cyl disp hp drat wt qsec vs am gear carb
# Merc 450SE 16.4 8 275.8 180 3.07 4.07 17.4 0 0 3 3
# Merc 450SL 17.3 8 275.8 180 3.07 3.73 17.6 0 0 3 3
# Merc 450SLC 15.2 8 275.8 180 3.07 3.78 18.0 0 0 3 3
Also works with dplyr
.
library(magrittr)
mtcars %>% dplyr::filter(eval(choice))
# mpg cyl disp hp drat wt qsec vs am gear carb
# Merc 450SE 16.4 8 275.8 180 3.07 4.07 17.4 0 0 3 3
# Merc 450SL 17.3 8 275.8 180 3.07 3.73 17.6 0 0 3 3
# Merc 450SLC 15.2 8 275.8 180 3.07 3.78 18.0 0 0 3 3