2011-04-29 107 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"); 
     } 
}