将 R 函数作为 Java 方法参数传递
Passing an R function as a Java method parameter
我有一个问题,几天来一直在努力解决。问题听起来像这样:
我在 R 中有一个函数:
f <- function(x) {
x ^ 3 - x ^ 2 - 4 * x + 2;
}
但我想在Java中使用它,例如如下:double y = f(5)
.
我该怎么做?
现在,我在 R 中使用 rJava 包来使用 java 代码。我需要将此函数作为参数发送到 java 方法并在那里计算函数(当然我可以在 R 中调用函数并只发送结果,但事实并非如此,我需要函数Java 整体)。
假设您正在使用 REngine
API 您想要构造一个函数调用并对其求值:
// 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());
你会得到
Result: 82.0
显然,如果您想在 R 端保持 f
的功能,您可以使用 new REXPSymbol("f")
而不是 fn
。
PS:如果您想快速得到答案,请考虑使用 rJava/JRI 邮件列表 stats-rosuda-devel。
您还可以使用 FastR,它是基于 GraalVM 的 R 实现。与 FastR 等效的是:
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);
此处有更多详细信息:https://medium.com/graalvm/faster-r-with-fastr-4b8db0e0dceb
我有一个问题,几天来一直在努力解决。问题听起来像这样:
我在 R 中有一个函数:
f <- function(x) {
x ^ 3 - x ^ 2 - 4 * x + 2;
}
但我想在Java中使用它,例如如下:double y = f(5)
.
我该怎么做?
现在,我在 R 中使用 rJava 包来使用 java 代码。我需要将此函数作为参数发送到 java 方法并在那里计算函数(当然我可以在 R 中调用函数并只发送结果,但事实并非如此,我需要函数Java 整体)。
假设您正在使用 REngine
API 您想要构造一个函数调用并对其求值:
// 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());
你会得到
Result: 82.0
显然,如果您想在 R 端保持 f
的功能,您可以使用 new REXPSymbol("f")
而不是 fn
。
PS:如果您想快速得到答案,请考虑使用 rJava/JRI 邮件列表 stats-rosuda-devel。
您还可以使用 FastR,它是基于 GraalVM 的 R 实现。与 FastR 等效的是:
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);
此处有更多详细信息:https://medium.com/graalvm/faster-r-with-fastr-4b8db0e0dceb