将purrr::map2()与dbplyr配合使用 [英] Using purrr::map2() with dbplyr
本文介绍了将purrr::map2()与dbplyr配合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从一个表("positons")中选择行,其中某个特定列("position")的值在另一个("my_range")表中定义的范围内,然后从"my_range"表中添加分组标记。
我可以使用tibble和几个purrr::map2
调用来实现这一点,但同样的方法不适用于dbplyr database-tibble。这是预期的行为吗?如果是,是否应该采取不同的方法来使用dbplyr执行此类任务?
下面是我的示例:
library("tidyverse")
set.seed(42)
my_ranges <-
tibble(
group_id = c("a", "b", "c", "d"),
start = c(1, 7, 2, 25),
end = c(5, 23, 7, 29)
)
positions <-
tibble(
position = as.integer(runif(n = 100, min = 0, max = 30)),
annotation = stringi::stri_rand_strings(n = 100, length = 10)
)
# note: this works as I expect and returns a tibble with 106 obs of 3 variables:
result <- map2(.x = my_ranges$start, .y = my_ranges$end,
.f = function(x, y) {between(positions$position, x, y)}) %>%
map2(.y = my_ranges$group_id,
.f = function(x, y){
positions %>%
filter(x) %>%
mutate(group_id = y)}
) %>% bind_rows()
# next, make an in-memory db for testing:
con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")
# copy data to db
copy_to(con, my_ranges, "my_ranges", temporary = FALSE)
copy_to(con, positions, "positions", temporary = FALSE)
# get db-backed tibbles:
my_ranges_db <- tbl(con, "my_ranges")
positions_db <- tbl(con, "positions")
# note: this does not work as I expect, and instead returns a tibble with 0 obsevations of 0 variables:
# database range-based query:
db_result <- map2(.x = my_ranges_db$start, .y = my_ranges_db$end,
.f = function(x, y) {
between(positions_db$position, x, y)
}) %>%
map2(.y = my_ranges_db$group_id,
.f = function(x, y){
positions_db %>%
filter(x) %>%
mutate(group_id = y)}
) %>% bind_rows()
推荐答案
dbplyr
将R
转换为SQL
。SQL
中不存在列表。map
创建列表。因此,无法将map
转换为SQL
。
主要是dplyr
函数和一些base
函数是翻译的,据我了解,他们也在tidyr
函数上工作。使用dbplyr
时,请尝试在您的方法中使用SQL
逻辑,否则它很容易中断。
这篇关于将purrr::map2()与dbplyr配合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文