【发布时间】:2018-07-22 03:49:45
【问题描述】:
我需要创建一个使用dplyr 执行数据库调用的包装函数。
首先创建一个可重现的示例:
library("DBI")
library("dplyr")
conn = DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")
df = expand.grid(indate = as.character(as.POSIXct(seq(as.Date('2017/06/06'), as.Date('2018/02/12'), by="day"))), name = c("Canada","Japan","USA"), stringsAsFactors = FALSE)
copy_to(conn, df, "lineups_country",
temporary = FALSE,
indexes = list(
"indate",
"name"
)
)
这是在没有包装函数的情况下运行良好的代码:
res = tbl(conn, table)
# filter the country
res = res %>% filter(name %in% c("Canada","Japan"))
# filter the date
res = res %>% filter(indate >= "2018-01-01")
res %>% show_query()
df2=res %>% collect()
unique(df$name);unique(df2$name)
min(df$indate);min(df2$indate)
现在要创建包装函数,我已经阅读了文档https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html
然而事情对我来说还不是很清楚,尤其是关于引号/引用。
这是我尝试过的:
myFun = function(conn, table,
dateCol = "indate",
startDate = as.POSIXct("2018-01-01"),
key = list(name = c("Australia","Japan"))) {
on.exit({dbDisconnect(conn)})
res = tbl(conn, table)
res %>% show_query()
# filter the country
countryCol = names(key)
enquo_country <- enquo(countryCol) #enquo_country <- rlang::sym(countryCol) #
res = res %>% filter(!!enquo_country %in% key[[1]])
res %>% show_query()
# filter the date
enquo_dateCol <- enquo(dateCol) #enquo_country <- rlang::sym(names(key)) #
res = res %>% filter(!!enquo_dateCol >= as.character(startDate))
res %>% show_query()
return(res %>% collect())
}
给出错误:
匹配错误(x, table, nomatch = 0L):“匹配”需要向量 论据
【问题讨论】: