2011-04-29 121 views
1

我正在尝试使用Java运行R。我在我的Mac上安装了R,并且从终端使用过很多次。通过Java从终端运行R

在终端,启动R,一个简单的类型 “R”

例:

Macintosh-11:Desktop myname$ R 

R version 2.12.2 (2011-02-25) 
Copyright (C) 2011 The R Foundation for Statistical Computing 
ISBN 3-900051-07-0 
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit) 

R is free software and comes with ABSOLUTELY NO WARRANTY. 
You are welcome to redistribute it under certain conditions. 
Type 'license()' or 'licence()' for distribution details. 

    Natural language support but running in an English locale 

R is a collaborative project with many contributors. 
Type 'contributors()' for more information and 
'citation()' on how to cite R or R packages in publications. 

Type 'demo()' for some demos, 'help()' for on-line help, or 
'help.start()' for an HTML browser interface to help. 
Type 'q()' to quit R. 

> 

所以,我想要做的是通过Java运行R,通过终端的内容。所以,我写了自己的Java类:

public class javar { 

     public static void main(String[] args) throws Exception { 
       Runtime.getRuntime().exec("R"); 
     } 
} 

然而,当我编译,然后执行,使用

java javar 

我没有看到[R开始。我只是看到程序完成执行,然后终端准备好另一个命令。

我该如何实现我想要做的?

+0

你们是不是要运行脚本或有一个互动的控制台? – Clint 2011-04-29 15:21:55

+0

尝试用Rgui而不是R? – 2011-04-29 15:27:58

+0

[当Runtime.exec()不会](http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html) – 2011-04-29 15:35:52

回答

3

当我遇到你的问题时,我结束了使用JRI,它不仅创建一个R/Java连接,而且允许你交换两者的矩阵和向量。

虽然我不建议这样做,但您的方法可能有效,但R启动后不会“挂起”,它只会执行任何操作并退出。尝试添加“--vanilla”选项,显然喂一些代码,它与--file = yourScript.R并最终使用参数--args

public class javar { 

     public static void main(String[] args) throws Exception { 
       Runtime.getRuntime().exec("R --vanilla --file=yourScript.R"); 
     } 
}