Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter dataframe on the fly

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

You may use an expression and evaluate 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading