Original address: http://www.douban.com/note/85247917/
Everyone reproduced also explained the original address, respect for the work of the author's achievements.
Absrtact: Using R to build statistical Analysis Server, Java through TCP/IP protocol to interact with R server, input analysis data and parameters, obtain statistical analysis results.
Steps:
1. Set up the Rserve server, thus can monitor the statistic analysis request
Reference article: R with Java integration (http://www.lijian001.com/r/blog_comment.asp?article_id=199)
Install R: $ sudo apt-get install R-base
Launch and enter R environment: $ r
Install Rserve package:> install.packages ("Rserve")
Load Rserve Package:> library ("Rserve")
Start Rserve (default is Demon mode): > Rserve
At this end of the preparation of R is ready, Rserve started that use Q () Exit R Environment, Rserve is still running.
2. Download the Rserve jar package so that you can directly invoke the API you have already done without having to dwell on the TCP/IP protocol at R-side
Address: http://www.rforge.net/Rserve/files/
There are two jar packs: Rengine.jar and Rserveengine.jar, and it's not clear why the API could not be placed in a jar package for easy deployment.
3. Write Java code to invoke Rserve
The simplest of several invocation methods:
Assigning an array to a variable
Rconnection.assign ("Dataa", arrayobject);
Here Dataa and Datab are two array variable names that will perform a T-Test on both the DATAA and Datab data and return the corresponding console output for the R end.
Rconnection.eval ("Paste" (Capture.output (T.test ("+ Dataa +", "+ Datab +")), collapse=\ "\\n\"). Asstring ()
You can also guide the plot picture in R to Java, and the byte array object returned in the following code can be exported to a JPG file by FileOutputStream. This code should have a lot to optimize the place, but I can not find the tmp.jpg storage path, had to forget:
public static byte[] BoxPlot (rconnection C, String dataaname, String databname) throws Rexpmismatchexception, Rengineexce ption{
String device = "jpeg";
Rexp XP = C.parseandeval ("Try" ("+ Device +" (' tmp.jpg ', quality=90));
C.parseandeval ("BoxPlot + Dataaname +", "+ Databname +"); Dev.off () ");
XP = C.parseandeval ("R=readbin" (' tmp.jpg ', ' raw ', ' 1024*1024 '); Unlink (' tmp.jpg '); r ");
return Xp.asbytes ();
}
PostScript: There is also a way to build the use of R's own dynamic link library to directly invoke the analysis method, my personal preference client/server this way, because it feels so layered clear, once the problem is easy to locate the bug.