我正在学习如何从 R 中查询 SQLite dbs,并使用glue_sql()
. 下面是我的工作流程中子查询的简化示例。有没有一种方法可以创建s10_wtX
而不s20_wtX
使用paste0()
,如下面的代码所示?
library(DBI)
library(dplyr)
library(glue)
# example database
set.seed(1)
ps <- data.frame(plot = rep(1:3, each = 4),
spp = rep(1:3*10, 2),
wtX = rnorm(12, 10, 2) %>% round(1))
con <- dbConnect(RSQLite::SQLite(), "")
dbWriteTable(con, "ps", ps)
# species of interest
our_spp <- c(10, 20)
# for the spp of interest, sum wtX on each plot
sq <- glue_sql(paste0(
'SELECT ps.plot,\n',
paste0('SUM(CASE WHEN ps.spp = ', our_spp,
' THEN (ps.wtX) END) AS s', our_spp,
'_wtX',
collapse = ',\n'), '\n',
' FROM ps
WHERE ps.spp IN ({our_spp*}) -- spp in our sample
GROUP BY ps.plot'),
.con = con)
# the result of the query should look like:
dbGetQuery(con, sq)
plot s10_wtX s20_wtX
1 1 21.9 10.4
2 2 11.0 22.2
3 3 9.4 13.0
在我的实际工作流程中,我有两种以上的兴趣,所以我宁愿不完整地写出每一行(例如,SUM(CASE WHEN ps.spp = 10 THEN (ps.wtX) END) AS s10_wtX
)。