【发布时间】:2021-06-17 16:37:31
【问题描述】:
我确实有一个使用 dbplyr 到 SQL 表的远程连接。
其中一个表由一个 ID 列和其他几个存储 0 和 1 值的列组成(SQL bit - 从 R 端解释为布尔值 TRUE/FALSE 值),从 R 我只想得到每个 1 的总数行。
在 R 中很简单,使用例如 rowSums() 的常用表,不幸的是它不能通过 dbplyr 工作(没有 SQL 等效项)。
由于基础表的大小,我不想collect()数据。
在这样的情况下如何做到这一点?
library(dplyr)
# Local case
DF <- tibble(ID = LETTERS[1:3], col1 = c(1,1,1), col2 = c(1,1,0), col3 = c(1,0,0))
DF %>%
summarise(sum = rowSums(select(., -1)))
# sum
# 1 3
# 2 2
# 3 1
# If DF is a remote SQL table, therefore one would get the following error message:
# Error: nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC SQL Server Driver][SQL Server]'rowSums' is not a recognized built-in function name. [Microsoft][ODBC SQL Server Driver][SQL Server]
编辑 - 添加最小可复制示例
关注@Simon.S.A.在 MRE 下方回复:
# Table creation
DF <- tibble(ID = LETTERS[1:3], col1 = c(1,1,1), col2 = c(1, 1,0), col3 = c(1,0,0))
colnames(DF) <- c("col 1", "col 2", "col 3", "col 4")
# SQL simulation
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
copy_to(con, DF)
con %>% tbl("DF") # just checking
#preparing formula
cols <- colnames(DF)[-1]
all_equations <- paste0("`", cols, "` = sum(`", cols,"`)")
# actual query
con %>%
tbl("DF") %>%
summarise(!!!rlang::parse_exprs(all_equations))
# Error: near "=": syntax error
# %>% show_query() shows a strange query, but I am no SQL expert as you understood.
# also tried:
# all_equations <- paste(cols ,"= sum(",cols,")")
# all_equations <- paste0("`[", cols, "]` = sum(`[", cols,"]`)")
【问题讨论】:
标签: r sql-server dbplyr