Search code examples
javarrjavagwmodel

Load data using rJava


I use rJava to integrate Java and R in my project.

I need to load GWmodel R package in my application and calculate the distance matrix from Java.

This is my function to load GWmodel and calculating distance matrix :

Rengine engine = new Rengine(new String[] { "--no-save" }, false, null);
engine.eval("library(GWmodel)");
engine.eval("data(LondonHP)");
engine.eval("DM <- gw.dist(dp.locat=coordinates(londonhp))");
double[][] matrix = engine.eval("DM").asMatrix();

But the code result an error :

Exception in thread "main" java.lang.NullPointerException
    at rjavaexm.RJavaExm.main(RJavaExm.java:30)

So, I want to know, is it possible to load R package and data using rJava from Java like code above?

Or are there any appropriate ways to do that?


Solution

  • I'm using maven so i have the following (generated from a simple maven project)

    mvn archetype:generate   -DgroupId=com.test.rserve  -DartifactId=com.test.rserve
    

    Select default choice.

    pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.test.rserve</groupId>
      <artifactId>com.test.rserve</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>com.test.rserve</name>
      <url>http://maven.apache.org</url>
      <dependencies>
      <dependency>  
        <groupId>org.rosuda.REngine</groupId>
        <artifactId>Rserve</artifactId>
        <version>1.8.1</version>
        </dependency>    
      </dependencies>
    </project>
    

    App.java

    package com.test.rserve;
    
    import org.rosuda.REngine.REXP;
    import org.rosuda.REngine.REXPMismatchException;
    import org.rosuda.REngine.Rserve.RConnection;
    import org.rosuda.REngine.Rserve.RserveException;
    
    
    public class App {
    
        public static void main(String[] args) throws RserveException,
                REXPMismatchException {
            RConnection c = new RConnection();
            REXP x = c.eval("R.version.string");
            System.out.println(x.asString());   
        c.eval("library(GWmodel)");
        c.eval("data(LondonHP)");
        c.eval("DM <- gw.dist(dp.locat=coordinates(londonhp))");
        REXP y = c.eval("dim(DM)[1]");
        System.out.println(y.asString());
        c.close();
        }
    }
    

    Make sure package Rserve is installed in your R environment.

    from R

    library(Rserve)
    Rserve()
    

    with maven (command line, another shell)

    mvn exec:java -Dexec.mainClass="com.test.rserve.App"
    

    We get with my settings :

    R version 3.2.4 (2016-03-16)
    316
    

    Don't forget to close the Rserve server/process afterwards ...