I am wondering if a function can be called SQLinside a function R?
Say, for example, that I have this dummy data and a function SQLwritten inPostgres 9.3
CREATE TABLE tbl (
id VARCHAR(2) PRIMARY KEY
,name TEXT
,year_born NUMERIC
,nationality TEXT
);
INSERT INTO tbl(id, name, year_born, nationality)
VALUES ('A1','Bill',2001,'American')
,('B1','Anna',1997,'Swedish')
,('A2','Bill',1991,'American')
,('B2','Anna',2004,'Swedish')
,('B3','Anna',1989,'Swedish')
,('A3','Bill',1995,'American');
CREATE FUNCTION retrieve_data(TEXT)
RETURNS TABLE ( id VARCHAR(2), name TEXT, year_born NUMERIC, nationality TEXT ) AS
$func$
SELECT id, name, year_born, nationality
FROM tbl
WHERE name=$1 OR nationality=$1
GROUP BY 1
ORDER BY 1
$func$ LANGUAGE sql
I can access this data and run the function in the environment Rthrough packages RPostgreSQLand sqldf, as shown below:
require(RPostgreSQL)
require(sqldf)
options(sqldf.RPostgreSQL.user = "****",
sqldf.RPostgreSQL.password = "****",
sqldf.RPostgreSQL.dbname = "test_db",
sqldf.RPostgreSQL.host = "localhost",
sqldf.RPostgreSQL.port = 5432)
sqldf("select * from retrieve_data('Bill')")
But is there a way to call the above function SQLin a function R, for example. like;
myfunc <- function(name) {
sqldf("select * from retrieve_data(name)")
}
myfunc('Bill')
Any pointers would be greatly appreciated, thanks!
UPDATE
Using the prefix $fnin the package sqldfas suggested by @G. Grothendieck
myfunc2 <- function(name){
fn$sqldf("select * from retrieve_data('$name')")
}
Or replace the above optionswith the code below to match @ dickoa's suggested answer
require(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv,
user="****",
password="****",
dbname="test_db",
host="localhost",
port=5432)