我想通過any()結合使用該函式來從 R 中的本地 SQLite 資料庫中獲取資料,group_by以過濾至少一行等于某個條件的組。最終學習 SQL 可能會有所幫助,但是,直到現在我設法使用 dbplyr 完成所有查詢,我希望也有針對此問題的 dplyr 解決方案。
db <- dbConnect(RSQLite::SQLite(), "test_db.sqlite")
test_table <- tibble(id = c(rep(1:3, each = 3)),
cond = c(rep("A", 8), "B"))
dbWriteTable(db, "table", test_table)
table <- tbl(db, "table")
表已經在記憶體中,我可以輕松完成我想要的事情
test_table %>%
group_by(id) %>%
filter(any(cond == "B"))
這給了我
id cond
<int> <chr>
1 3 A
2 3 A
3 3 B
但是,這不起作用:
table %>%
group_by(id) %>%
filter(any(cond == "B"))
它會導致以下錯誤:
error: no such function: any
是否有 dbplyr 解決方法?
uj5u.com熱心網友回復:
這是一個有效的解決方案:
library(dplyr)
library(DBI)
db <- dbConnect(RSQLite::SQLite(), "test_db.sqlite")
test_table <- tibble(id = c(rep(1:3, each = 3)),
cond = c(rep("A", 8), "B"))
test_table
### A tibble: 9 × 2
## id cond
## <int> <chr>
##1 1 A
##2 1 A
##3 1 A
##4 2 A
##5 2 A
##6 2 A
##7 3 A
##8 3 A
##9 3 B
dbWriteTable(db, "table", test_table)
table <- tbl(db, "table")
table %>%
group_by(id) %>%
filter(sum(cond == "B") > 0)
## Source: lazy query [?? x 2]
## Database: sqlite 3.38.0 [test_db.sqlite]
## Groups: id
# id cond
# <int> <chr>
#1 3 A
#2 3 A
#3 3 B
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451669.html
上一篇:Django/Python-更改未保存在資料庫中-AttributeError:'QuerySet'物件沒有屬性'reload'
