如何根据一个单一的值过滤一个远程表? [英] How to filter a remote table based on one single value?

查看:95
本文介绍了如何根据一个单一的值过滤一个远程表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 filter()在%中使用%,但是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

我的问题与多个selectInput值创建意外的dplyr(postgres)行为。似乎像这个问题也是众所周知的

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

推荐答案

把一些建议放在一起,对于我的场景来说,最好的方法可能是下面的一个。我不喜欢在如果语句嵌套 filter()的原因是我有多个过滤器从闪亮的应用程序的菜单项。因此,在源处理变量可以节省大量的输入。

Putting together some of the suggestions, the best approach for my scenario it's probably gonna be the one below. The reason why I don't like nesting the filter() in a if statement, is that I have multiple filter from menu items of a shiny app. Thus, manipulating the variable at the source saves me a lot of typing.

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

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

这篇关于如何根据一个单一的值过滤一个远程表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆