【问题标题】:How to group_by and summarize with list column dbplyr如何使用列表列 dbplyr 进行分组和汇总
【发布时间】:2021-12-26 20:22:33
【问题描述】:

我希望在数据库中执行以下操作,但使用 {dbplyr} 似乎不可能。还有其他方法吗?谢谢

library(dbplyr)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:dbplyr':
#> 
#>     ident, sql
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

# Desired Behavior
tbl <- tibble(g = c(1, 1, 1, 2, 2), x = c(4, 3, 6, 9, 2))
tbl %>%
  group_by(g) %>%
  summarize(list_x = list(x))
#> # A tibble: 2 x 2
#>       g list_x   
#>   <dbl> <list>   
#> 1     1 <dbl [3]>
#> 2     2 <dbl [2]>

# Current behavior
db <- memdb_frame(g = c(1, 1, 1, 2, 2), x = c(4, 3, 6, 9, 2))
db %>%
  group_by(g) %>%
  summarize(list_x = list(x))
#> Error: no such function: list

reprex package (v2.0.1) 于 2021 年 11 月 15 日创建

【问题讨论】:

  • 我不知道任何具有list 内部概念的数据库 - 这是一个 R 概念,而不是一个 db 概念,所以我怀疑它会自动从 R 转换为数据库。
  • 您可以连接字符串中的值,具体取决于您的数据库,它可能支持 JSON 条目,可能还有其他解决方案,但我们需要有关您正在使用的数据库以及您为什么想要的详细信息这样做 - 你的目标是什么,有什么意义?
  • 我正在使用 MSSQL Server。我想加入两个表,并从第一个表中过滤掉不在第二个变量的可能值列表中的元素。如果我的 SQL 更好,我知道可能有办法做到这一点,但这对我来说在这个论坛上更难提出。
  • 好吧,这种方式行不通。我建议努力阐明问题而不是尝试这种解决方案,否则我们会留下XY problem

标签: r dbplyr


【解决方案1】:

您可能做的最好的事情就是将所有文本连接成一个字符串。比如:

db <- memdb_frame(g = c(1, 1, 1, 2, 2), x = c(4, 3, 6, 9, 2))
db %>%
  group_by(g) %>%
  summarize(list_x = paste0(x, collapse = "|"))

然后,您可以将此新列作为文本而不是列表进行搜索。例如:

db %>% mutate(indicator = ifelse(grepl('4', list_x), 1, 0))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多