Renjin - how to use values ​​generated in java

I am using renjin, and I am trying to use values ​​generated in java code with r code, for example:

int x = 7; try { engine.eval("tmp<-c(x, 4)"); engine.eval("print(tmp)"); } catch (ScriptException ex) { ; } 

However, this does not work, as the engine apparently cannot work with x. Is there an easy way to solve this problem?

+4
source share
2 answers

You can combine the variable into a string as a literal, as I posted in a comment:

 engine.eval("tmp<-c(" + x + ", 4)"); 

This works because (I assume) the engine must evaluate literals (with value numbers instead of a variable), and the above expression essentially passes tmp<-c(7, 4) through the concatenation (combination) of strings and an integer value. I would try to run the command first to store the variable, and then refer to it, that is:

 engine.eval(x <- 7); 

Then try your original expression. I am not familiar with Range, so it shot a little in the dark.

+3
source

Renjin uses the javax.script interface, thanks to which you can interact with the R environment. See the documentation here: http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/

To set variables in the global R environment, you can use the put () method. Here are some examples:

 engine.put("x", 4); engine.put("y", new double[] { 1d, 2d, 3d, 4d }); engine.put("z", new org.renjin.sexp.DoubleArrayVector(1,2,3,4,5)); engine.put("obj", new HashMap()); 

Renjin will implicitly convert primitives, arrays of primitives, and java.lang.String instances to R. objects. Java objects will be wrapped as R external objects.

From R code, Renjin allows you to manipulate Java objects using the $ operator, for example:

 obj$put("a", 1) obj$put("b", 2) print(obj$size()) print(obj$get("b")) 

You can also provide your own implementations of R objects by extending classes in the org.renjin.sexp package. For instance:

 public class MyDoubleVector extends DoubleVector { public double getElementAsDouble(int index) { // lookup value in database return index; } public int length() { // query length in database return length; } } 
+5
source

Source: https://habr.com/ru/post/1497177/


All Articles