使用rJava从Java调用R脚本函数 [英] Calling R script function from Java using rJava

查看:936
本文介绍了使用rJava从Java调用R脚本函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求 -

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

I need to deploy a Java webservice in a server which internally executes a R scipt file. I googled about various solutions for calling R from Java and the best were rJava and Rserve. Using Rserve I can call R function BUT as I am running this in Windows it can not handle multiple requests at a time and I dont want to switch to Linux.

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

What I tried - I have used rJava to call a R function :

    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

任何形式的帮助将不胜感激。

推荐答案

问题是当我第二次接到网络服务时因为我们已经有一个Rengine实例而被绞死在第一次通话时创建的礼物。

The issue was when I am acessing the webservice for the 2nd time it got hanged because we already have an instance of Rengine present which was created at first call.

    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实例 Rengine re = Rengine.getMainEngine();

  • 关闭最后通过 re.end();

  • Check if any instance of Rengine is already present by Rengine re = Rengine.getMainEngine();
  • Shut down R in the end by re.end();

它可能很有帮助。谢谢。

It may be helpful. thanks.

这篇关于使用rJava从Java调用R脚本函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆