我有一个java代码,里面有R编程步骤,运行得非常好。但是相同的R编程步骤被提取到R文件(MyScript.r)中,我试图从我的java代码中调用这个文件。当我运行我的java代码似乎没有发生任何事情。我可能看起来对我想要达到的目标感到愚蠢,可能是因为我对R没有了解。所以需要你的帮助。
我的Java代码里面有R编程步骤。
package com.rtest;
import java.io.IOException;
import org.rosuda.JRI.Rengine;
public class RWithJavaTest {
public static void main(String a[]) {
// Create an R vector in the form of a string.
String javaVector = "c(1,2,3,4,5)";
// System.out.println("System.getProperty(\"java.library.path\")>>"+System.getProperty("java.library.path")); //Prints path in env var
// 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);
}
}
以上程序运行时,成功给出输出:3.0
带有R编程步骤的Java代码,包含在R文件中并从java代码调用R文件。
package com.rtest;
import java.io.IOException;
public class RWithJavaTest {
public static void main(String a[]) {
try {
System.out.println("before..");
Runtime.getRuntime().exec("Rscript D:\\MyScript.R");
System.out.println("after..");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
R脚本:
// Create an R vector in the form of a string.
String javaVector = "c(1,2,3,4,5)";
// System.out.println("System.getProperty(\"java.library.path\")>>"+System.getProperty("java.library.path")); //Prints path in env var
// 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);
我知道我在这里所做的事情是完全错误的,但在这里寻求2件事的帮助 1)如何纠正我的R脚本,使其在没有任何问题的情况下运行 2)调用R脚本的Java代码,所以一旦运行代码,我就能看到输出3.0。
答案 0 :(得分:0)
下面的代码行显然对我有用,它成功调用了R文件。
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/R/R-3.4.3/bin/Rscript.exe" ,"D:/RTest/MyScript.R");
pb.start();