Search code examples
javarmethodsrjava

Passing an R function as a Java method parameter


I have a problem that I'm trying to solve for a couple a days now. The problem sounds like this:

I have a function in R :

f <- function(x) {
  x ^ 3 - x ^ 2 - 4 * x + 2;
}

but I want to use it in Java, for example as follows: double y = f(5).

How can I do that?


Now, I'm using rJava package in R to use java code. I need to send this function as a parameter to a java method and calculate the function there (of course I can call the function in R and just send the result, but this is not the case, I need the function in Java as a whole).


Solution

  • Assuming you're using the REngine API you want to construct a call to the function an evaluate it:

    // get a reference to the function
    REXP fn = eng.parseAndEval("function(x) x ^ 3 - x ^ 2 - 4 * x + 2", null, false);
    
    // create a call and evaluate it
    REXP res = eng.eval(new REXPLanguage(new RList( new REXP[] {
                 fn, new REXPInteger(5)
                        })), null, true);
    System.out.println("Result: " + res.asDouble());
    

    and you'll get

    Result: 82.0
    

    Obviously, you can use new REXPSymbol("f") instead of fn if you want to keep the function as f on the R side.

    PS: if you want quick answers, consider using the rJava/JRI mailing list stats-rosuda-devel.