我在用着dplyr
的自动SQL后端从数据库表中查询子表。例如。
my_tbl <- tbl(my_db, "my_table")
where my_table
在数据库中看起来像
batch_name value
batch_A_1 1
batch_A_2 2
batch_A_2 3
batch_B_1 8
batch_B_2 9
...
我只想要来自的数据batch_A_#
,无论数量。
如果我用 SQL 写这个,我可以使用
select * where batch_name like 'batch_A_%'
如果我用 R 写这个,我可以使用几种方法来得到它:grepl()
, %in%
, or str_detect()
# option 1
subtable <- my_tbl %>% select(batch_name, value) %>%
filter(grepl('batch_A_', batch_name, fixed = T))
# option 2
subtable <- my_tbl %>% select(batch_name, value) %>%
filter(str_detect(batch_name, 'batch_A_'))
所有这些都会产生以下 Postgres 错误:HINT: No function matches the given name and argument types. You might need to add explicit type casts
那么,如何传入 SQL 字符串函数或匹配函数来帮助生成的 dplyr SQL 查询能够使用更灵活的函数范围filter
?
(仅供参考%in%
函数确实有效,但需要列出所有可能的值。这结合起来就可以了paste
列出一个列表,但在更一般的正则表达式情况下不起作用)