简体   繁体   English

从Java调用R语言/脚本

[英]Invoke R Language/script from java

How do we invoke R language / R script from java? 我们如何从Java调用R语言/ R脚本? Basically I need java kind of wrapper around R script. 基本上,我需要围绕R脚本的Java包装器。

  1. Data will be given to java layer say method setData(double[]) which should in turn sends to R script - let us say setDataR(double []) method. 数据将通过方法setData(double [])传递给Java层,该方法又应发送到R脚本-让我们说一下setDataR(double [])方法。

  2. R script will perform some computation say calls method double[] computeR(). R脚本将执行一些计算,例如调用方法double [] computeR()。

  3. Java program will get the computation result by invoking double[] getData() which in turn delegates to R script to get the computated data. Java程序将通过调用double [] getData()获得计算结果,而double [] getData()则委托给R脚本来获取计算数据。

How can this be performed by JRI, Rserv, Rcaller? JRI,Rserv,Rcaller如何执行此操作? I do not see any way to invoke Rscript methods? 我看不到任何调用Rscript方法的方法吗? Please send sample. 请发送样品。 It should be simular to JNI (java, C++) invocations. 它应该与JNI(java,C ++)调用类似。

  1. Does within jvm I think multiple threads cannot invoke R script call correct? 我认为在jvm中多个线程不能正确调用R脚本调用吗? Any work around? 有没有解决的办法?

Thanks 谢谢

The most simple way to use R from Java is using Runtime.exec("") , grabbing the response and parsing it. 从Java使用R的最简单方法是使用Runtime.exec("") ,获取响应并进行解析。 A typical example on how to run native instructions would be: 有关如何运行本机指令的典型示例为:

Process p = Runtime.getRuntime().exec("ls");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

From here, you can read and process the result printed to the standard output being buffered into stdInput . 从这里,您可以读取和处理打印到标准输出的结果,该结果被缓冲到stdInput

RCaller exactly does what you want. RCaller正是您想要的。 Suppose you have a double array 'a' that is defined as 假设您有一个双精度数组'a',定义为

double[] a = new double[] {1.0, 2.0, 3.0};

and you want to calculate the mean, median and standard deviation values. 并且您要计算平均值,中位数和标准偏差值。 Create a new instance of RCaller 创建一个新的RCaller实例

RCaller caller = new RCaller();
Globals.detect_current_rscript();
caller.setRscriptExecutable(Globals.Rscript_current);

RCode code = new RCode();


code.addDoubleMatrix("a", a);
code.addRCode("s <- list(mean=mean(a), median=median(a), sd=sd(a))");

caller.setRCode(code);

caller.runAndReturnResult("s");

double mean = caller.getParser().getAsDoubleArray("mean")[0];
double median = caller.getParser().getAsDoubleArray("median")[0];
double sd = caller.getParser().getAsDoubleArray("sd")[0];

and the variable median holds the value of 2.0 which is returned from the R script. 变量中位数保存从R脚本返回的值2.0。 For details visit the page here 有关详细信息,请访问此处页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM