Reserve java调用R语言

Rserve安装和加载:
> install.packages('Rserve')
> library(Rserve)
 
在R中启动: > Rserve() Starting Rserve:
 "D:\PROGRA~2\R\R-31~1.0\library\Rserve\libs\i386\Rserve.exe" 

或者在命令行下启动:
R CMD Rserve
Rserve: Ok, ready to answer queries.
 
新建一个java工程,加载jar包:
  
  
  
  
    - REngine.jar
    - RserveEngine.jar
这两个包在安装目录的R\R-3.1.0\library\Rserve\java目录下
java测试代码:
  1. public class PhonePrediction {  
  2.     public static void main(String[] args) throws RserveException, REXPMismatchException {  
  3.         RConnection re = new RConnection("127.0.0.1");  
  4.         REXP x = re.eval("R.version.string");  
  5.         System.out.println(x.asString());  
  6.         double[] arr = re.eval("rnorm(20)").asDoubles();  
  7.         for (double a : arr) {  
  8.             System.out.print(a + ",");  
  9.         }  
  10.         //保存为图像文件  
  11.         File tempFile = null;  
  12.         try {  
  13.             re.assign("x", arr);   
  14.             tempFile = File.createTempFile("test-"".jpg");  
  15.             String filePath = tempFile.getAbsolutePath();  
  16.             re.eval("jpeg('d://test-1.jpg')");  
  17.             re.eval("plot(x)");   
  18.             re.eval("dev.off()");  
  19.         } catch (IOException e) {  
  20.             e.printStackTrace();  
  21.         } catch (REngineException e) {  
  22.             e.printStackTrace();  
  23.         } finally {  
  24.             re.close();   
  25.   
  26.         }  
  27.     }  
  28. }  
输出结果:
R version 3.1.0 (2014-04-10) 
1.0430051899098896,0.671152708470419,0.03148965245438613,1.787869887719384,-2.08155433250965,-1.4168523658229992,-0.8520930614700867,-0.7301950652654462,1.4214651003583285,0.10718589295501241,-0.5064964081419379,-1.0498486125440167,0.1824419576545006,-0.8918871851488132,-0.4150752116861583,-0.7139279436213399,0.06678515999067902,-1.1849271689141667,-0.05695413043401658,0.12468011012699255,
对应的图像文件test-1.jpg:
Reserve java调用R语言_第1张图片

你可能感兴趣的:(R语言)