原来R可以被java调用

 在试验中,为了求每天价格的波动率,我决定采用ARCH模型,细看了基本原理后,觉得自己去实现挺难的。我的系统是用java写的,遗憾的是找不到java写的ARCH源码,难道,我就真得要自己写了吗?幸运的是,我发现R中有这样的ARCH包,那么,我该如何更好的利用R呢,一个疑问升起,R能不能集成到我的java系统啊?答案是:yes!

        R是越来越火了,什么样的算法包都能找到,以前觉得matlab和sas是数据挖掘与分析领域的屠龙宝刀和倚天剑,那么R就是明教的圣火令了,也是一大神器。

        在R中有一个rJava的包,相当于,java调用R的接口,有这样的接口,那么java调用R中算法,便如举手之劳了。下面简单介绍下配置过程。

        1、下载和安装R软件;

        2、在命令窗口,输入:install.packages("rJava"),下载和安装rJava包;

        3、配置环境变量;注意这是r软件的安装文件里面的一些文件。这是我的相关配置:D:\R-2.11.1\library\rJava\jri ;  D:\R-2.11.1\bin ;

        4、引用用jar包到eclipse项目;三个包的名字分别是:JRI.jar\REngine.jar和JRIEngine.jar,在第二步下载的文件当中。

        5、就是写程序测试了。

        下面是个例子,把代码提出来,供参考:

        

001import java.io.*;
002import java.awt.Frame;
003import java.awt.FileDialog;
004  
005import java.util.Enumeration;
006  
007import org.rosuda.JRI.Rengine;
008import org.rosuda.JRI.REXP;
009import org.rosuda.JRI.RList;
010import org.rosuda.JRI.RVector;
011import org.rosuda.JRI.RMainLoopCallbacks;
012  
013class TextConsole implements RMainLoopCallbacks
014{
015    public void rWriteConsole(Rengine re, String text, int oType) {
016        System.out.print(text);
017    }
018      
019    public void rBusy(Rengine re, int which) {
020        System.out.println("rBusy("+which+")");
021    }
022      
023    public String rReadConsole(Rengine re, String prompt, int addToHistory) {
024        System.out.print(prompt);
025        try {
026            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
027            String s=br.readLine();
028            return (s==null||s.length()==0)?s:s+"\n";
029        } catch (Exception e) {
030            System.out.println("jriReadConsole exception: "+e.getMessage());
031        }
032        return null;
033    }
034      
035    public void rShowMessage(Rengine re, String message) {
036        System.out.println("rShowMessage \""+message+"\"");
037    }
038      
039    public String rChooseFile(Rengine re, int newFile) {
040    FileDialog fd = new FileDialog(new Frame(), (newFile==0)?"Select a file":"Select a new file", (newFile==0)?FileDialog.LOAD:FileDialog.SAVE);
041    fd.show();
042    String res=null;
043    if (fd.getDirectory()!=null) res=fd.getDirectory();
044    if (fd.getFile()!=null) res=(res==null)?fd.getFile():(res+fd.getFile());
045    return res;
046    }
047      
048    public void   rFlushConsole (Rengine re) {
049    }
050      
051    public void   rLoadHistory  (Rengine re, String filename) {
052    }           
053      
054    public void   rSaveHistory  (Rengine re, String filename) {
055    }           
056}
057  
058public class Rtest {
059    public static void main(String[] args) {
060    // just making sure we have the right version of everything
061    if (!Rengine.versionCheck()) {
062        System.err.println("** Version mismatch - Java files don't match library version.");
063        System.exit(1);
064    }
065        System.out.println("Creating Rengine (with arguments)");
066        // 1) we pass the arguments from the command line
067        // 2) we won't use the main loop at first, we'll start it later
068        //    (that's the "false" as second argument)
069        // 3) the callbacks are implemented by the TextConsole class above
070        Rengine re=new Rengine(args, false, new TextConsole());
071        System.out.println("Rengine created, waiting for R");
072        // the engine creates R is a new thread, so we should wait until it's ready
073        if (!re.waitForR()) {
074            System.out.println("Cannot load R");
075            return;
076        }
077  
078        /* High-level API - do not use RNI methods unless there is no other way
079            to accomplish what you want */
080        try {
081            REXP x;
082            re.eval("data(iris)",false);
083            System.out.println(x=re.eval("iris"));
084            // generic vectors are RVector to accomodate names
085            RVector v = x.asVector();
086            if (v.getNames()!=null) {
087                System.out.println("has names:");
088                for (Enumeration e = v.getNames().elements() ; e.hasMoreElements() ;) {
089                    System.out.println(e.nextElement());
090                }
091            }
092            // for compatibility with Rserve we allow casting of vectors to lists
093            RList vl = x.asList();
094            String[] k = vl.keys();
095            if (k!=null) {
096                System.out.println("and once again from the list:");
097                int i=0; while (i<k.length) System.out.println(k[i++]);
098            }           
099  
100            // get boolean array
101            System.out.println(x=re.eval("iris[[1]]>mean(iris[[1]])"));
102            // R knows about TRUE/FALSE/NA, so we cannot use boolean[] this way
103            // instead, we use int[] which is more convenient (and what R uses internally anyway)
104            int[] bi = x.asIntArray();
105            {
106                int i = 0; while (i<bi.length) { System.out.print(bi[i]==0?"F ":(bi[i]==1?"T ":"NA ")); i++; }
107                System.out.println("");
108            }
109              
110            // push a boolean array
111            boolean by[] = { true, false, false };
112            re.assign("bool", by);
113            System.out.println(x=re.eval("bool"));
114            // asBool returns the first element of the array as RBool
115            // (mostly useful for boolean arrays of the length 1). is should return true
116            System.out.println("isTRUE? "+x.asBool().isTRUE());
117  
118            // now for a real dotted-pair list:
119            System.out.println(x=re.eval("pairlist(a=1,b='foo',c=1:5)"));
120            RList l = x.asList();
121            if (l!=null) {
122                int i=0;
123                String [] a = l.keys();
124                System.out.println("Keys:");
125                while (i<a.length) System.out.println(a[i++]);
126                System.out.println("Contents:");
127                i=0;
128                while (i<a.length) System.out.println(l.at(i++));
129            }
130            System.out.println(re.eval("sqrt(36)"));
131        } catch (Exception e) {
132            System.out.println("EX:"+e);
133            e.printStackTrace();
134        }
135          
136        // Part 2 - low-level API - for illustration purposes only!
137        //System.exit(0);
138          
139        // simple assignment like a<-"hello" (env=0 means use R_GlobalEnv)
140        long xp1 = re.rniPutString("hello");
141        re.rniAssign("a", xp1, 0);
142  
143        // Example: how to create a named list or data.frame
144        double da[] = {1.2, 2.3, 4.5};
145        double db[] = {1.4, 2.6, 4.2};
146        long xp3 = re.rniPutDoubleArray(da);
147        long xp4 = re.rniPutDoubleArray(db);
148          
149        // now build a list (generic vector is how that's called in R)
150        long la[] = {xp3, xp4};
151        long xp5 = re.rniPutVector(la);
152  
153        // now let's add names
154        String sa[] = {"a","b"};
155        long xp2 = re.rniPutStringArray(sa);
156        re.rniSetAttr(xp5, "names", xp2);
157  
158        // ok, we have a proper list now
159        // we could use assign and then eval "b<-data.frame(b)", but for now let's build it by hand:       
160        String rn[] = {"1", "2", "3"};
161        long xp7 = re.rniPutStringArray(rn);
162        re.rniSetAttr(xp5, "row.names", xp7);
163          
164        long xp6 = re.rniPutString("data.frame");
165        re.rniSetAttr(xp5, "class", xp6);
166          
167        // assign the whole thing to the "b" variable
168        re.rniAssign("b", xp5, 0);
169          
170        {
171            System.out.println("Parsing");
172            long e=re.rniParse("data(iris)", 1);
173            System.out.println("Result = "+e+", running eval");
174            long r=re.rniEval(e, 0);
175            System.out.println("Result = "+r+", building REXP");
176            REXP x=new REXP(re, r);
177            System.out.println("REXP result = "+x);
178        }
179        {
180            System.out.println("Parsing");
181            long e=re.rniParse("iris", 1);
182            System.out.println("Result = "+e+", running eval");
183            long r=re.rniEval(e, 0);
184            System.out.println("Result = "+r+", building REXP");
185            REXP x=new REXP(re, r);
186            System.out.println("REXP result = "+x);
187        }
188        {
189            System.out.println("Parsing");
190            long e=re.rniParse("names(iris)", 1);
191            System.out.println("Result = "+e+", running eval");
192            long r=re.rniEval(e, 0);
193            System.out.println("Result = "+r+", building REXP");
194            REXP x=new REXP(re, r);
195            System.out.println("REXP result = "+x);
196            String s[]=x.asStringArray();
197            if (s!=null) {
198                int i=0; while (i<s.length) { System.out.println("["+i+"] \""+s[i]+"\""); i++; }
199            }
200        }
201        {
202            System.out.println("Parsing");
203            long e=re.rniParse("rnorm(10)", 1);
204            System.out.println("Result = "+e+", running eval");
205            long r=re.rniEval(e, 0);
206            System.out.println("Result = "+r+", building REXP");
207            REXP x=new REXP(re, r);
208            System.out.println("REXP result = "+x);
209            double d[]=x.asDoubleArray();
210            if (d!=null) {
211                int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
212                System.out.println("");
213            }
214            System.out.println("");
215        }
216        {
217            REXP x=re.eval("1:10");
218            System.out.println("REXP result = "+x);
219            int d[]=x.asIntArray();
220            if (d!=null) {
221                int i=0; while (i<d.length) { System.out.print(((i==0)?"":", ")+d[i]); i++; }
222                System.out.println("");
223            }
224        }
225  
226        re.eval("print(1:10/3)");
227          
228    if (true) {
229        // so far we used R as a computational slave without REPL
230        // now we start the loop, so the user can use the console
231        System.out.println("Now the console is yours ... have fun");
232        re.startMainLoop();
233    } else {
234        re.end();
235        System.out.println("end");
236    }
237    }
238}
1输出结果如下:
1<A id=ematt:138 class=highslide href="/content/uploadfile/201208/f3ccdd27d2000e3f9255a7e3e2c4880020120804140622.jpg" target=_blank getParams="null" jQuery1346517118937="6"><IMG border=0 alt=点击查看原图 src="/content/uploadfile/201208/thum-f3ccdd27d2000e3f9255a7e3e2c4880020120804140622.jpg"></A>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值