How to execute Java code in R
R is a popular programming language. It is mostly sought out for data and statistical analysis as well as for machine learning. It provides various libraries which render an environment favorable to those mentioned above. Furthermore, it is harnessed by many quantitative analysts as it has proven to be handy when it comes to data cleansing and importing.
Drawbacks
R is a core functional programming language, although object-oriented programming does exist within R, to put it plainly, it is not at the same level as other languages such as Java. It is also not as efficient due to the fact it is an interpreted language. Hence it is more computationally economical to run Java code in R.
Running Java in R
R offers a package known as rJava , this package allows us to run java code within our R file. In other words, this library provides a bridge between R and Java, enabling us to access Java fields from R.
Syntax
j_obj <- .jnew(class , arg)
Parameter value
class: This is the type of the object, for instance, string, integer, double, etc.arg: This is the argument for the object.
Return value
The .jnew method returns the object of class type.
Code example
Let's look at the code below:
library(rJava).jinit()str_val <- .jnew(class="java.lang.String" , "Hello World").jstrVal(str_val)int_val <- .jnew(class = "java.lang.Integer", "1").jstrVal(int_val)
Code explanation
Line 1: We import the
rJavapackage.Line 2: We initialize the Java virtual machine.
Line 4: We create a java object of the type
java.lang.String. The value of that string isHello World.And we store the instance of the object created intostr_val.Line 5: We display the value of
str_valto console as a string.Line 7: We create a Java object of type
java.lang.Integer. The value of that string isHello World. And we store the instance of the object created intoint_val.Line 8: We display the value of
int_valto console as a string.
Free Resources