来自RConnection(JRI)的R源文件"找不到函数"

时间:2016-08-01 16:49:35

标签: r rjava rserve rjdbc

我试图从org.rosuda.REngine.Rserve.RConnection中获取一个R脚本文件,然后从该脚本调用一个函数,但是我得到了,"错误:找不到函数& #34;主"

从终端启动Rserve

> require(Rserve)
Loading required package: Rserve
> Rserve()
Starting Rserve...
 "C:\Users\slenzi\DOCUME~1\R\WIN-LI~1\3.3\Rserve\libs\x64\Rserve.exe"
> Rserve: Ok, ready to answer queries.
Error: could not find function "main"

外部脚本rdbcTest1.R

require(RJDBC)

main <- function() {
    jdbcDriver <- JDBC(driverClass = dbDriverClass, classPath = dbDriverPath)
    jdbcConnection <- dbConnect(jdbcDriver, dbUrl, dbUser, dbPwd)
    dbResult <- dbGetQuery(jdbcConnection, dbQuery)
    dbDisconnect(jdbcConnection)
    return(dbResult)
}

Java代码

import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngine;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.RList;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;

REXP result = null;
RConnection c = null;
try {

    c = new RConnection();

    String driverPath = "C:/temp/ojbdc6.jar";
    String scriptPath = "C:/temp/rdbcTest1.R";

    c.assign("dbUser", "foo");
    c.assign("dbPwd", "******");// commented out
    c.assign("dbUrl", "jdbc:oracle:thin:@myhost:1511:ecogtst");
    c.assign("dbDriverClass", "oracle.jdbc.driver.OracleDriver");
    c.assign("dbDriverPath", driverPath);       

    // assign query to execute
    c.assign("dbQuery", "SELECT count(*) FROM prs.members");            

    String evalSource = String.format("try(source(\"%s\", local=TRUE), silent=TRUE)", scriptPath);

    c.eval("evalSource");

    // debug
    result = c.eval("ls()");
    logger.info("REXP debug => " + result.toDebugString());         

    result = c.eval("main()");

} catch (RserveException e) {
    logger.error("error running script test, " + e.getMessage());
} finally {
    if(c != null){
        c.close();
    }
}

输出

evaluating => try(source("C:/temp/rdbcTest1.R", local=TRUE), silent=TRUE)
REXP debug => org.rosuda.REngine.REXPString@61c6bc05[6]{"dbDriverClass","dbDriverPath","dbPwd","dbQuery","dbUrl","dbUser"}

Error: could not find function "main"
error running oracle script test, eval failed, request status: error code: 127

直接从R终端运行脚本,它工作正常。从RConnection运行时,我可以看到我分配的变量(c.assign(...))的值,但不能看到源脚本中的main()函数。

在采购脚本方面我缺少什么?如何从脚本中访问函数?

感谢。

** 更新 **

我有以下工作,但如果有人知道为什么source()似乎在上面的示例中没有用,请告诉我!

RConnection c = ...
REXP x = c.parseAndEval("try(eval(parse(file=\"C:/temp/rdbcTest3.R\")), silent=TRUE)")

0 个答案:

没有答案