I struggle to call a plr function in postgreSQL from a R-script and use it in ggplot2 - geom_function. The following examples are extremly simplified but hopefully show the issue.
Let's assume I have the following plr function:
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$;
To call this from ggplot - geom_function I thought, I could write the following simple wrapper function to do the query (I use the rpostgres package):
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)
}
But if I now call this function from ggplot, I get the following warning message and an empty plot:
Computation failed in
stat_function()
: Query requires 2 params; 102 supplied.
The ggplot code looks as follows:
ggplot() +
geom_function(fun = myWrapper , args = list(a = 5))
If I write the plr function in R instead and call this from geom_function, everything works fine. If I call the myWrapper directly (outside ggplot) with just one value for x and a, respectively, everything works fine as well.
So, what do I have to change?