【问题标题】:Calling R script function from Java using rJava使用 rJava 从 Java 调用 R 脚本函数
【发布时间】:2016-10-12 08:39:31
【问题描述】:

我的要求 -

我需要在内部执行 R scipt 文件的服务器中部署 Java 网络服务。我在 Google 上搜索了从 Java 调用 R 的各种解决方案,最好的是 rJava 和 Rserve。使用 Rserve 我可以调用 R 函数,但是因为我在 Windows 中运行它,它不能一次处理多个请求,我不想切换到 Linux。

[编辑]

我尝试了什么 - 我使用 rJava 调用了 R 函数:

    String[] args = new String[3];
    args[0] = "--quiet"; // Don't print startup message
    args[1] = "--no-restore"; // Don't restore anything
    args[2] = "--no-save";
    String rFilePath = "D:/Dataset_Info/AI-KMS_v2.0/tika/src/main/resources/HSConcordance.R";
    Rengine engine = new Rengine(args, false, null);
    if (!engine.waitForR()) {
        System.out.println("Cannot load R");
    }
    System.out.print("JRI R-Engine call: ");
    engine.eval("source(\"" + rFilePath + "\")");
    REXP value = engine.eval("as.integer(a<-simple())");
    int a = value.asInt();
    System.out.println(a);

Maven 依赖 -

    <dependency>
        <groupId>com.github.lucarosellini.rJava</groupId>
        <artifactId>JRI</artifactId>
        <version>0.9-7</version>
    </dependency>
    <dependency>
        <groupId>com.github.lucarosellini.rJava</groupId>
        <artifactId>REngine</artifactId>
        <version>0.9-7</version>
    </dependency>
    <dependency>
        <groupId>com.github.lucarosellini.rJava</groupId>
        <artifactId>JRIEngine</artifactId>
        <version>0.9-7</version>
    </dependency>

我的 R 脚本文件 -

simple<-function(){
a=1
return(a)
}

输出 - JRI R-Engine 调用:1 然后它挂起。我调试了一下,发现卡在Thread.class

我们将不胜感激。

【问题讨论】:

    标签: java r web-services rjava


    【解决方案1】:

    问题是当我第二次访问 web 服务时它被挂起,因为我们已经有一个 Rengine 实例存在,它是在第一次调用时创建的。

        Rengine re = Rengine.getMainEngine();
        if(re == null){
            re=new Rengine (new String [] {"--vanilla"}, false, null);
            if (!re.waitForR())
            {
                System.out.println ("Cannot load R");
                return "failure";
            }
        }
        re.eval("source(\"" + rFilePath + "\")");
        re.eval("copyfile(\""+filePath+"\")");
        re.end();
    

    注意几点-

    • 通过Rengine re = Rengine.getMainEngine();检查Rengine的任何实例是否已经存在
    • 最后由re.end();关闭R

    这可能会有所帮助。谢谢。

    【讨论】:

      猜你喜欢
      • 2012-02-09
      • 1970-01-01
      • 2016-08-27
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多