Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering by variable to allow returning all rows

Tags:

r

dplyr

I have code like the following:

library(dplyr)
my_values <- rep(1:10, 10)
my_df <- data.frame(my_values, "points")

user_values <- c(2, 3)

filter(my_df, my_values %in% user_values)

The user provides certain values to filter by. In certain situations, the filter should not be "active", meaning rows with all values of "my_values" should be retained.

What can I assign to user_values to achieve this? I tried assigning NULL, but that returns 0 rows. Assigning TRUE coerces it to the value of 1.

I know I could assign my_df$my_values (or unique(my_df$my_values)), but filtering by that would probably take a long time when there are thousands of possible values for the variable to take. So I'm searching for a more elegant solution.

like image 559
mkranj Avatar asked Oct 28 '25 03:10

mkranj


2 Answers

I would use TRUE as it could be understood as "everything" semantically. NULL would be also an option as pointed out by @Konrad and eventually it breaks down to a matter of taste / overall conventions in your project:

nrow(my_df)
# [1] 100

user_values <- c(2, 3)
my_df %>% 
   filter(isTRUE(user_values) | my_values %in% user_values) %>%
   nrow()
# [1] 20

user_values <- TRUE
my_df %>% 
   filter(isTRUE(user_values) | my_values %in% user_values) %>%
   nrow()
# [1] 100

user_values <- NULL
my_df %>% 
   filter(is.null(user_values) | my_values %in% user_values) %>%
   nrow()
# [1] 100
like image 194
thothal Avatar answered Oct 29 '25 20:10

thothal


You can use if inside the filter function call:

filter(my_df, if(is.null(user_values)) TRUE else my_values %in% user_values)
like image 31
Konrad Rudolph Avatar answered Oct 29 '25 20:10

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!