使用 JAVA 程序运行 R 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32373680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run R script using JAVA program
提问by Tiya
I am new to R programming. I have created a simple R script and trying to run it using JAVA class, but I am unable to do it.
我是 R 编程的新手。我创建了一个简单的 R 脚本并尝试使用 JAVA 类运行它,但我无法做到。
I have tried by using Rserve as well as rJava. Using Rserve, code execution stopped after creating instance of "RConnection" whereas using rJava giving exception "java.lang.UnsatisfiedLinkError: jri.dll: Can't find dependent libraries".
我尝试过使用 Rserve 和 rJava。使用 Rserve,代码执行在创建“RConnection”实例后停止,而使用 rJava 给出异常“java.lang.UnsatisfiedLinkError:jri.dll:找不到依赖库”。
The JAVA class code is as below:
JAVA类代码如下:
For rJava:
对于 rJava:
import org.rosuda.JRI.Rengine;
public class Temp {
public static void main(String a[]) {
// Create an R vector in the form of a string.
String javaVector = "c(1,2,3,4,5)";
// Start Rengine.
Rengine engine = new Rengine(new String[] { "--no-save" }, false, null);
// The vector that was created in JAVA context is stored in 'rVector' which is a variable in R context.
engine.eval("rVector=" + javaVector);
//Calculate MEAN of vector using R syntax.
engine.eval("meanVal=mean(rVector)");
//Retrieve MEAN value
double mean = engine.eval("meanVal").asDouble();
//Print output values
System.out.println("Mean of given vector is=" + mean);
}
}
For Rserve:
对于 Rserve:
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class Temp {
public static void main(String a[]) {
RConnection connection = null;
System.out.println("line 10");
try {
// Create a connection to Rserve instance running on default port 6311
System.out.println("line 15");
connection = new RConnection();
System.out.println("line 17");
//Note four slashes (\\) in the path
connection.eval("source('D:\\RExamples\\helloworld.R')");
System.out.println("line 19");
int num1=10;
int num2=20;
int sum=connection.eval("myAdd("+num1+","+num2+")").asInteger();
System.out.println("The sum is=" + sum);
} catch (RserveException e) {
e.printStackTrace();
} catch (REXPMismatchException e) {
e.printStackTrace();
}
}
}
Please let me know if my question is not clear to you or if you want to know anything else. Thanks in advance.
如果我的问题对您来说不清楚,或者您想知道其他任何事情,请告诉我。提前致谢。
采纳答案by Malaka Gunawardhana
You just want to call an external application: wouldn't the following work?
你只想调用一个外部应用程序:下面的方法不行吗?
Runtime.getRuntime().exec("Rscript myScript.R");
Credit goes to stackoverflow itself
回答by jfcorugedo
There are two different approach to connect Java and R.
有两种不同的方法来连接 Java 和 R。
If you want to use JRI, you have to start your java program using the JVM parameter -Djava.library.path
pointing at the folder that contains JRI library.
如果要使用JRI,则必须使用-Djava.library.path
指向包含 JRI 库的文件夹的 JVM 参数启动 Java 程序。
For instance:
例如:
$JAVA_HOME/bin/java -Djava.library.path=/app/vendor/R/lib/R/library/rJava/jri/ -jar target/myapp.jar
If you have trouble finding JRI installation directory, try to look for the JRI SO library:
如果找不到 JRI 安装目录,请尝试查找 JRI SO 库:
find / -name "libjri.*"
In addition, make sure you have created R_HOME and LD_LIBRARY_PATH in your environment:
此外,请确保您已在您的环境中创建了 R_HOME 和 LD_LIBRARY_PATH:
- R_HOME: Pointing to your local R installation (Ej: /Library/Frameworks/R.framework/Resources)
- LD_LIBRARY_PATH: Pointing to R lib directory as well as JRI directory (EJ: $LD_LIBRARY_PATH:/app/vendor/R/lib/R/lib:/app/vendor/R/lib/R/bin)
- R_HOME:指向本地 R 安装(Ej:/Library/Frameworks/R.framework/Resources)
- LD_LIBRARY_PATH: 指向 R lib 目录以及 JRI 目录 (EJ: $LD_LIBRARY_PATH:/app/vendor/R/lib/R/lib:/app/vendor/R/lib/R/bin)
On the other hand, if you want to use Rserve, you need to start Rserve in a separate process, and then create a RConnection from your java process.
另一方面,如果你想使用Rserve,你需要在一个单独的进程中启动 Rserve ,然后从你的 java 进程创建一个 RConnection 。
For example:
例如:
if(LOGGER.isInfoEnabled()) {
LOGGER.info("Starting RServe process...");
}
ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", String.format("echo 'library(Rserve);Rserve(FALSE,args=\"--no-save --slave --RS-conf %s\")'|%s --no-save --slave", rserveConf, rexe));
builder.inheritIO();
Process rProcess = builder.start();
if(LOGGER.isInfoEnabled()) {
LOGGER.info("Waiting for Rserve to start...");
}
int execCodeResult = rProcess.waitFor();
if(execCodeResult != SUCCESS_CODE) {
LOGGER.error(String.format("Unexpected error code starting RServe: %d", execCodeResult));
} else {
LOGGER.error("RServe started successfully");
}
if(LOGGER.isInfoEnabled()) {
LOGGER.info("Opening connection to RServe daemon....");
}
REngine engine = new RConnection();
if(LOGGER.isInfoEnabled()) {
LOGGER.info(String.format("Obtaining R server version: %d", ((RConnection)engine).getServerVersion()));
}
//Perform some engine.parseAndEval("....");
rserveConfis the path to Rserv conf file and rexeis the full path to R executable.
rserveConf是 Rserv conf 文件的路径,而rexe是 R 可执行文件的完整路径。
For instance, in my MacOS computer I can start Rserve executing this line:
例如,在我的 MacOS 计算机中,我可以启动 Rserve 执行以下行:
/bin/sh -c "echo 'library(Rserve);Rserve(FALSE,args=\"--slave --RS-conf /Users/me/Documents/test/rserve.conf\")'|/Library/Frameworks/R.framework/Versions/3.2/Resources/bin/exec/R --no-save --slave"
This command outputs something like this:
此命令输出如下内容:
Starting Rserve:
/Library/Frameworks/R.framework/Resources/bin/R CMD /Library/Frameworks/R.framework/Versions/3.2/Resources/library/Rserve/libs//Rserve --slave
Rserv started in daemon mode.
Make sure to specify "--slave" parameter when you start Rserve.
确保在启动 Rserve 时指定“--slave”参数。
If you want to see more examples, I have a demo project that use both approaches, JRI and RServe, in my github:
如果您想查看更多示例,我的 github 中有一个使用 JRI 和 RServe 两种方法的演示项目:
回答by Jake
An alternative is to use r's OpenCpu package. This is a very simple server (single threaded unfortunately) that receives r function calls over http and returns the output as the response.
另一种方法是使用 r 的 OpenCpu 包。这是一个非常简单的服务器(不幸的是单线程),它通过 http 接收 r 函数调用并将输出作为响应返回。
I have used it to interface with java.
我用它来与java接口。