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

I am doing filter() with %in% , but the way dplyr translates the query seems wrong. In fact, the %in% operator works fine with more than one value, but not when only one element is present. In my original scenario, the filtering values ​​are dynamic, so 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, duplicating multiple selectInput values ​​creates unexpected dplyr (postgres) behavior . This issue seems to be well known.

+6
source share
2 answers

Combining some of the suggestions, the best approach for my scenario is likely to be as follows. The reason I don't like the embedding of filter() in an if is because I have some filter from menu items of a brilliant application. Thus, manipulating a variable in the source saves a lot of input.

 a <- c("UA") b <- if(length(a)>1) a else c(a,"") tbl(my_db, "dplyr") %>% filter(carrier %in% b) 

or

  a <- c("UA") varToFilterFor <- rep(a ,2) tbl(my_db, "dplyr") %>% filter(carrier %in% varToFilterFor) 
0
source

I can not imagine why your code crashes. But while someone cannot provide a better solution, here is a simple approach 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) } 
+3
source

All Articles