dplyr:连接到外部数据库时在 summarize() 中使用自定义函数

dplyr: use a custom function in summarize() when connected to external database

在使用 dplyr 从外部数据库中提取数据时,有没有办法在摘要语句中使用自定义函数? 我无法创建可用的虚拟数据,因为这是特定于数据库的,但假设您有一个包含三个字段的 table:product、true_positive 和 all_positive。这是我要使用的代码:

getPrecision <- function(true_positive, all_positive){
  if_else(sum(all_positive, na.rm = TRUE) == 0, 0,
          (sum(true_positive) / sum(all_positive , na.rm = TRUE)))
}

database_data %>%
    group_by(product) %>%
    summarize(precision = getPrecision(true_positive, all_positive)) %>% collect

这是错误:postgresqlExecStatement(conn, statement, ...) 中的错误: RS-DBI 驱动程序:(无法检索结果:错误:函数 getprecision(整数,整数)不存在

要了解错误消息,您可以使用 show_query 而不是 collect 来查看发送到数据库的 SQL 代码:

database_data %>%
    group_by(product) %>%
    summarize(precision = getPrecision(true_positive, all_positive)) %>%  
    show_query

<SQL>
SELECT "product", getPrecision("true_positive", "all_positive") AS "precision"
FROM "database_table"
GROUP BY "product"

如您所见,此 SQL 期望 getPrecision 函数在服务器上可用,但事实并非如此。

一个潜在的解决方案是先收集 table 数据,然后再在 R 客户端中应用此功能:

database_data %>%
    collect %>%
    group_by(product) %>%
    summarize(precision = getPrecision(true_positive, all_positive)) 

如果这不可能,因为 table 太大,您必须在服务器上实现 SQL 中的功能:

SELECT 
  "product", 
  CASE WHEN sum(all_positive)=0 THEN 0 ELSE sum(true_positive)/sum(all_positive) END AS "precision"
FROM "database_table"
GROUP BY "product"