当将条件指定为字符串时,对数据库使用dplyr :: filter的方法是什么?

问题描述 投票:0回答:1

当条件指定为字符串时,我不知道如何在数据库中使用dplyr::filterdplyr::filter_在这里很简单,但已弃用。

suppressPackageStartupMessages(library(dplyr))
con <- DBI::dbConnect(RSQLite::SQLite(), dbname = ":memory:")
copy_to(con, iris, "iris", temporary = FALSE)
iris_db <- tbl(con, "iris")
filter_str <- "Species == 'setosa'"

首先尝试对数据框进行过滤

iris_db %>% collect() %>% filter(eval(parse(text = filter_str))) %>% count()
#> # A tibble: 1 x 1
#>       n
#>   <int>
#> 1    50

现在使用filter_在数据库上尝试此操作>

iris_db %>% filter_(filter_str) %>% collect() %>% count()
#> Warning: filter_() is deprecated. 
#> Please use filter() instead
#> 
#> The 'programming' vignette or the tidyeval book can help you
#> to program with filter() : https://tidyeval.tidyverse.org
#> This warning is displayed once per session.
#> # A tibble: 1 x 1
#>       n
#>   <int>
#> 1    50

现在使用filter在数据库上尝试。这失败。

iris_db %>% filter(eval(parse(text = filter_str))) %>% collect() %>% count()
#> Warning: Named arguments ignored for SQL parse
#> Error: near "AS": syntax error

这就是失败的原因

iris_db %>% filter(eval(parse(text = filter_str))) %>% show_query() 
#> <SQL>
#> Warning: Named arguments ignored for SQL parse
#> SELECT *
#> FROM `iris`
#> WHERE (eval(parse('Species == ''setosa''' AS `text`)))

reprex package(v0.3.0)在2020-03-26创建

当条件指定为字符串时,我不知道如何在数据库中使用dplyr :: filter。 dplyr :: filter_在这里很简单,但已弃用。 preventPackageStartupMessages(library(dplyr))con&...

r dplyr
1个回答
0
投票

使用parse_expr中的rlang

© www.soinside.com 2019 - 2024. All rights reserved.