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测试代码:public class PhonePrediction { public static void main(String[] args) throws RserveException, REXPMismatchException { RConnection re = new RConnection("127.0.0.1"); REXP x = re.eval("R.version.string"); System.out.println(x.asString()); double[] arr = re.eval("rnorm(20)").asDoubles(); for (double a : arr) { System.out.print(a + ","); } //保存为图像文件 File tempFile = null; try { re.assign("x", arr); tempFile = File.createTempFile("test-", ".jpg"); String filePath = tempFile.getAbsolutePath(); re.eval("jpeg('d://test-1.jpg')"); re.eval("plot(x)"); re.eval("dev.off()"); } catch (IOException e) { e.printStackTrace(); } catch (REngineException e) { e.printStackTrace(); } finally { re.close(); } } }
输出结果:
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: