我想在 dbplyr
查询中选择分组数据集的第一行。为此,我想使用 summarise
函数。
在正常的 dplyr 管道中,这可以正常工作:
library(tidyverse)
library(DBI)
library(dbplyr)
mtcars %>%
arrange(cyl) %>%
group_by(cyl) %>%
summarise(test = head(mpg, 1))
# A tibble: 3 × 2
cyl test
<dbl> <dbl>
1 4 22.8
2 6 21
3 8 18.7
现在我想将这个原理转移到 dbplyr 查询中:
# Creating a simple test connection
con <- dbConnect(RSQLite::SQLite(), "")
# Inserting test table
dbWriteTable(con, "mtcars", mtcars)
con %>%
tbl("mtcars") %>%
arrange(cyl) %>%
group_by(cyl) %>%
summarise(test = head(cyl, 1)) %>%
collect()
Error in `collect()`:
! Failed to collect lazy table.
Caused by error:
! no such function: head
Run `rlang::last_trace()` to see where the error occurred.
但是,head()
函数无法在 SQL 语句中使用 dbplyr 进行转换,因此会出现错误。
谁能帮我找到一种替代方法来获取 dbplyr
查询中分组数据集的第一个元素?
(同样,我还需要一个函数来获取分组记录的最后元素)。
最佳答案
我无法确切说明为什么不能直接在 dbplyr 中使用 dplyr 语法,也许请参阅此 GitHub 问题以获取更多信息:first() doesn't work in summaries
但这里有一个适用于两者的替代方案:
mtcars %>%
arrange(cyl) %>%
group_by(cyl) %>%
mutate(First = first(mpg), Last = last(mpg)) %>%
select(cyl, First, Last) %>%
distinct()
con %>%
tbl("mtcars") %>%
arrange(cyl) %>%
group_by(cyl) %>%
mutate(First = first(mpg), Last = last(mpg)) %>%
select(cyl, First, Last) %>%
distinct()
# # Source: SQL [3 x 3]
# # Database: sqlite 3.41.2 []
# # Groups: cyl
# # Ordered by: cyl
# cyl First Last
# <dbl> <dbl> <dbl>
# 1 4 22.8 21.4
# 2 6 21 19.7
# 3 8 18.7 15
关于sql - 如何在 dbplyr-query 中的 summarise-function 中获取组的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76882429/