monj
monj

Reputation: 33

If you have created a function in R, how do you call it in Java using Renjin?

Let's say I have created a function in R like

bin <- function(arg1, arg2, arg3) {
//some code here
}

I am using Renjin to run R on the JVM. From my Java program, I want to call my R function bin. I know you need to use something similar to this first just to access R

ScriptEngineManager manager = new ScriptEngineManager();
// create a Renjin engine:
ScriptEngine engine = manager.getEngineByName("Renjin");

but once that is done, how exactly do I access my R function? This function is stored in a separate file. I know that to run an R script (let's call this script.R), you use

engine.eval(new java.io.FileReader("script.R"));

but that doesn't allow argument passing in functions in the file... it just runs the whole thing.

Would I have to just rewrite the function using R/Renjin in my Java program? Or is there an efficient way to call the function?

Thank you!

Upvotes: 3

Views: 972

Answers (1)

mjkallen
mjkallen

Reputation: 478

When you run

engine.eval(new java.io.FileReader("script.R"));

the script.R file is parsed and the statements in the file are executed in the global environment. If your file only defines the function, then it will indeed not be called.

There are a few options to execute the function:

  1. extend script.R to include a call to bin, e.g.

    bin <- function(arg1, arg2, arg3) {
    //some code here
    }
    bin(arg1 = 1, arg2 = 2, arg3 = 3)
    
  2. evaluate script.R, construct and evaluate the command in the Java code, e.g.

    engine.eval(new java.io.FileReader("script.R"));
    

    followed by

    engine.eval("bin(arg1 = " + 1 + ", arg2 = " + 2 + ", arg3 = " + 3 + ")");
    
  3. evaluate script.R, create variables in the global environment, and execute the bin function:

    engine.eval(new java.io.FileReader("script.R"));
    engine.eval("arg1 <- 1; arg2 <- 2; arg3 <- 3");
    engine.eval("bin(arg1, arg2, arg3)");
    

Each option gives you different levels of flexibility, therefore you can experiment to see which works best for you.

Upvotes: 4

Related Questions