Reputation: 4921
I have program written with R. I can run it from the R GUI and it spits out results.
Is there a way to run that program from Java?
Upvotes: 3
Views: 8373
Reputation: 3234
You can also use FastR, which is R engine implemented on top of JVM. Using it from Java is as simple as:
Context context = Context.newBuilder("R").allowAllAccess(true).build();
int result = context.eval("R", "sum").execute(new int[] {3,4,5}).asInt();
context.eval("R", "print('you can eval any R code here');");
This is an example of how to pass data from Java to R and make it look like a data.frame
. This is another example of how to redirect R graphics into Java Graphics2D
object.
A more detailed description is in this article: https://medium.com/graalvm/faster-r-with-fastr-4b8db0e0dceb
and on the GraalVM website: http://graalvm.org
Upvotes: 1
Reputation: 390
I think one of the easiest possibilities to execute R code from some other environment is REST webservice.
For instance if you have an R-Script called example.R with the following function:
#* @get /hello
hello <- function() {
print("hello")
}
You can run the following:
library(plumber)
r <- plumb("example.R")
r$run(port=8080)
If you then call the page
http://localhost:8080/hello
your R code will be executed.
If you want to execute it from Java the solution could be:
URL url = new URL("http://localhost:8080/hello");
URLConnection connection = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader( (connection.getInputStream())));
String result = br.readLine();
Upvotes: 2