ashcrok
ashcrok

Reputation: 244

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).

Upvotes: 0

Views: 771

Answers (2)

Steves
Steves

Reputation: 3234

You can also use FastR, which is GraalVM based R implementation. The equivalent with FastR would be:

Context ctx = Context.newBuilder("R").allowAllAccess(true).build();
Value fun = ctx.eval("R", "function(x) x ^ 3 - x ^ 2 - 4 * x + 2")
System.out.println(fun.execute(5);

More details here: https://medium.com/graalvm/faster-r-with-fastr-4b8db0e0dceb

Upvotes: 0

Simon Urbanek
Simon Urbanek

Reputation: 13932

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.

Upvotes: 1

Related Questions