Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a remote table based on one single value?

Tags:

r

dplyr

I am doing a filter() using %in% but the way dplyr translates the query seems incorrect. In fact, the %in% operator works fine with more than one value, but it doesn't when only a single element is present. In my original scenario the filtering values are dynamic, thus I would like to have a function that works in both cases.

my_db <- src_mysql(dbname = "dplyr", 
                   host = "dplyr.csrrinzqubik.us-east-1.rds.amazonaws.com", 
                   port = 3306, 
                   user = "dplyr",
                   password = "dplyr")
tbl(my_db, "dplyr") %>% filter(carrier %in% c("UA","AA")) #works
tbl(my_db, "dplyr") %>% filter(carrier %in% c("UA")) #doesn't work

My question is a duplicate of multiple selectInput values create unexpected dplyr (postgres) behavior. Seems like this issue is well-known too

like image 827
Dambo Avatar asked Jul 07 '16 17:07

Dambo


1 Answers

I can't offer any insights into why your code fails. But until someone can provide a better solution, here is a simple work-around that provides "a function that works in both cases".

my.carriers <- c("UA","AA")
my.carriers <- c("UA")

if (length(my.carriers)>1) {
  tbl(my_db, "dplyr") %>% filter(carrier %in% my.carriers)
} else {
  tbl(my_db, "dplyr") %>% filter(carrier == my.carriers)
}
like image 112
dww Avatar answered Sep 24 '22 07:09

dww