I have a java code which has R programming steps in it which is running perfectly fine. But the same R programming steps are extracted into a R file (MyScript.r) and I tried to call this file from my java code. When I run my java code nothing seems to be happening. I may look dumb with what I'm trying to achieve, may be it's true as I don't have knowledge on R. So required your help on this.
My Java code with R programming steps inside it.
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);
}
}
The above program when run, successfully giving me the output: 3.0
Java code with R programming steps included in R file and calling the R file from the java code.
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 script:
// 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);
I know what I did here is something completely wrong but seeking help on 2 things here.
1) How to correct my R Script so that it runs with out any issues
2) Java code to call the R Script, so I can see the output 3.0 once I run the code.