call SQL function within R function

删除回忆录丶 提交于 2019-12-04 10:00:35

The trick is to use shQuote and sprintf but there are clever way to do that I'm sure.

library(sqldf)
library(RPostgreSQL)

options(sqldf.RPostgreSQL.user = "****",
        sqldf.RPostgreSQL.dbname = "****",
        sqldf.RPostgreSQL.host = "localhost",
        sqldf.RPostgreSQL.port = 5432)

myfunc <- function(name)
    sqldf(sprintf("select * from retrieve_data(%s)", shQuote(name)))

myfunc('Bill')
##   id name year_born nationality
## 1 A1 Bill      2001    American
## 2 A2 Bill      1991    American
## 3 A3 Bill      1995    American

If you want to avoid quoting the string then you can use

drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, dbname = "tempdb")
myfunc2 <- function(name)
    dbGetQuery(con, "select * from retrieve_data($1)", name)

myfunc2("Bill")
##   id name year_born nationality
## 1 A1 Bill      2001    American
## 2 A2 Bill      1991    American
## 3 A3 Bill      1995    American
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!