我很难从 R 脚本中调用 postgreSQL 中的 plr 函数并在 ggplot2 - geom_function 中使用它。以下示例非常简化,但希望能说明问题。
假设我有以下 plr 函数:
CREATE OR REPLACE FUNCTION public.mypgfunc(
x numeric,
a numeric)
RETURNS numeric
LANGUAGE 'plr'
COST 100
VOLATILE PARALLEL UNSAFE
AS $BODY$
return (x*a)
$BODY$;
要从 ggplot - geom_function 我想调用它,我可以编写以下简单的包装函数来执行查询(我使用 rpostgres 包):
myWrapper <- function(x , a) {
con <- dbConnect(drv = RPostgres::Postgres() , dbname='mydb')
q <- dbSendQuery(con , "select mypgfunc( $1 , $2 )")
dbBind(q , c(x,a))
y <- dbFetch(q)
dbClearResult(q)
dbDisconnect(con)
return(y)
}
但是,如果我现在从 ggplot 调用此函数,我会收到以下警告消息和一个空图:
计算失败
stat_function()
:查询需要 2 个参数;提供 102 个。
ggplot 代码如下所示:
ggplot() +
geom_function(fun = myWrapper , args = list(a = 5))
如果我在 R 中编写 plr 函数并从 geom_function 调用它,一切正常。如果我直接(在 ggplot 之外)调用 myWrapper,分别只为 x 和 a 提供一个值,那么一切正常。
那么,我需要改变什么?