How to use R language in java

Java is currently a very popular programming language, with its unique programming thinking for complex programming, but Java lacks data analysis and visualization capabilities. However, the R language is specially born for statistics. The R language has developed rapidly in recent years and can be used for machine learning, data mining, and data visualization. To bridge this gap, we can combine JAVA with R

combination

JAVA calls R language through Rserve.

One, the environment

System: win10

JDK:1.8

R:3.3.1

eclipse

Two: Install the R language

About how to install the R language, you can check the previous blog

Preparations in the Three R's

First install the Rserve package in R

install.packages("Rserve")



Before using Rserve() to start the service, you need to use

library(Rserve) load Rserve

then start the service

Rserve()

If the following statement appears, it means that the service has been started:

Starting Rserve..."D:PROGRA~1RR-33~1.1libraryRservelibsx64Rserve.exe"


Now that we have the Rserve server running, we can create a Java program in eclipse , use Rserve to communicate with R , and call R functions in the Java code.

Four Eclipse using R language

I created a java project in RserveProject , and then right-clicked the project name properties—Java Build Path—Librares—Add External Jar... Load REngine.jar and Rserve.jar two jar packages, I installed R in D: , so those two packages are in D:R R-3.3.4 library Rserve java . Everyone finds it according to their actual situation.

code show as below

import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
import org.rosuda.REngine.REXPMismatchException;;


public class Temp {


public static void main(String[] args) throws REXPMismatchException {
RConnection connection = null;
System.out.println("平均值");
try {
// 创建对象
connection = new RConnection();
String vetor = "c(1,2,3,4)";
connection.eval("meanVal<-mean(" + vetor +")");
double mean = connection.eval("meanVal").asDouble();
System.out.println("the mean of given vector is=" + mean);
} catch (RserveException e) {
e.printStackTrace();
}
System.out.println("execute script");
try {
connection.eval("source('F:/myAdd.R')");// The path here can also be written like this D:\\\\myAdd.R
int num1 = 20;
int num2 = 10;
int sum = connection.eval("myAdd(" + num1 + "," + num2 + ")").asInteger();
System.out.println("the sum=" + sum);
} catch (RserveException e) {
System. out.println(e);
e.printStackTrace();
}
connection.close();
}

}

The script files in the F disk are as follows


Results of the


Since Rserve runs as a server, it can handle multiple requests at the same time. This also means when we start an instance of Rserve with the command.

We start the Rserve instance from the R console, there are three instances as follows.

Rserve(port=5011)Rserve(port=5012)Rserve(port=5013)

Now with these 3 separate instances, the 3 threads can easily connect to the 3 instances:

//Thread 1 connects to an instance running on port 5011 RConnection connection = newRConnection("hostIP_or_hostName",5011);//Thread 2 connects to an instance running on port 5012 RConnection connection = newRConnection("hostIP_or_hostName",5012); //Thread 3 connects to the instance running on port 5013 RConnection connection = newRConnection("hostIP_or_hostName",5013);

The second method java uses R language

This is a relatively simple and convenient method. This time we need to write a simple R language script, and then run the R script to open the Rserve service. In this case, we don't have to open R first and then enter the program to open the Rserve service every time we run the Java program. Isn't this very simple and convenient. Using this method, and the R language, draw a simple word cloud.

First, we create an R script:

library(Rserve)Rserve()</span>

I saved it as a Rserve.R file and put it in this directory (m yStartR is my own new folder): D:R-3.3.1 myStartR

For importing the jar package and installing wordclound in R as before

We create a new class to initialize the Rserve service. code show as below:

package com;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
/**
 * Start Rserve service
 */
public class Rservel {
private static String R_EXE_PATH = "D:/R-3.4 .3/bin/R.exe";
private static String R__PATH = "D:/R-3.4.3/myStartR/Rserve.R";


public static RConnection getRConnection() {
try {
RConnection rConnection = new RConnection();
return rConnection;
} catch (RserveException e) {
System.out.println("Starting Rserve service...");
try {
Runtime rn = Runtime.getRuntime();
/*
* It is not recommended to write directly as rn. exec("R_EXE_PATH R__PATH"),
* If you learn to draw the previously defined R_EXE_PATH, R__PATH will prompt * These two variables are not used*
* There may be an error when running, and the prompt error is as follows: * java.io.IOException: Cannot run program
* "D:Program": CreateProcess error=2, The system cannot find the specified file.
*/
String[] commandArgs = { R_EXE_PATH, R__PATH };
rn.exec(commandArgs);
Thread.sleep(5000);
} catch (Exception e2) {
e2.printStackTrace();
}
return getRConnection();
}
}
}

The main class is as follows

package com;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import javax.swing.JFrame;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.Rserve.RConnection;


public class WordCloud extends JFrame {
private static final long serialVersionUID = 1L;
static Image img;


public static void main(String[] args) throws Exception {
WordCloud wc = new WordCloud();
REXP xp = wc.getRobj();// 获得R对象
wc.PlotDemo(xp, wc);// 错误
}


private REXP getRobj() throws Exception {
RConnection c = Rservel.getRConnection();
c.setStringEncoding("utf8");// 设置字符编码
REXP Rservesion = c.eval("R.version.string");
System.out.println(Rservesion.asString());
System.out.println("n----------绘图演示--------");
System.out.println("");
REXP xp = c.parseAndEval("jpeg('test.jpg',quality=90)");
c.eval("library(wordcloud)");
c.voidEval("colors=c('red','blue','green','yellow','purple')");
c.parseAndEval("data(SOTU);wordcloud(SOTU,min.freq=10,colors=colors);dev.off()");
xp = c.parseAndEval("r=readBin('test.jpg','raw',3000*3000);unlink('test.jpg');r");
return xp;
}


public void PlotDemo(REXP xp, JFrame f) throws Exception {
img = Toolkit.getDefaultToolkit().createImage(xp.asBytes());
MediaTracker mediaTracker = new MediaTracker(this);
mediaTracker.addImage(img, 0);
mediaTracker.waitForID(0);
f.setTitle("Test Image");
f.setSize(img.getWidth(null), img.getHeight(null));
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
f.setVisible(true);
}


public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}

}


The result is as follows



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324748754&siteId=291194637