将查询转换为数据库可能会出现问题str_detect
:
b <- tbl(con,"pays")
filter(b,str_detect(nom,"^D")) %>% explain
#<SQL>
#SELECT *
#FROM "pays"
#WHERE (STRPOS("nom", '^D') > 0)
#<PLAN>
#Seq Scan on pays (cost=0.00..5.31 rows=74 width=13)
# Filter: (strpos(nom, '^D'::text) > 0)
b %>% filter(str_detect(nom, "^D")) %>% count
## Source: lazy query [?? x 1]
## Database: postgres 9.6.1 [h2izgk@localhost:5432/postgres]
# n
# <dbl>
#1 0
不幸的是,STRPOS(我使用的是 PostgreSQL)无法识别 '^' 的含义并且查询失败。所以你应该使用另一个函数,我发现 `grepl 很好:
filter(b,grepl("^D",nom)) %>% explain
#<SQL>
#SELECT *
#FROM "pays"
#WHERE (("nom") ~ ('^D'))
#<PLAN>
#Seq Scan on pays (cost=0.00..4.76 rows=54 width=13)
# Filter: (nom ~ '^D'::text)
b %>% filter(grepl("^D", nom))
## Source: lazy query [?? x 3]
## Database: postgres 9.6.1 [h2izgk@localhost:5432/postgres]
# nom pays code
# <chr> <chr> <chr>
#1 DANEMARK 101 208
#2 DOUALA "" 120
#3 DAKAR "" 686
#4 DJIBOUTI 399 262
结果是正确的。在您的示例中,collect
解决了问题,因为它首先将整个表下载到 R 内存中,然后在str_detect
不转换为 SQL 的情况下应用。但效率不高。