原来R可以被java调用

来源:互联网 发布:矩阵特征分解证明 编辑:程序博客网 时间:2024/06/13 05:56

 在试验中,为了求每天价格的波动率,我决定采用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、就是写程序测试了。

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

        

view source
print?
001importjava.io.*;
002importjava.awt.Frame;
003importjava.awt.FileDialog;
004  
005importjava.util.Enumeration;
006  
007importorg.rosuda.JRI.Rengine;
008importorg.rosuda.JRI.REXP;
009importorg.rosuda.JRI.RList;
010importorg.rosuda.JRI.RVector;
011importorg.rosuda.JRI.RMainLoopCallbacks;
012  
013classTextConsole implementsRMainLoopCallbacks
014{
015    publicvoidrWriteConsole(Rengine re, String text, intoType) {
016        System.out.print(text);
017    }
018      
019    publicvoidrBusy(Rengine re, intwhich) {
020        System.out.println("rBusy("+which+")");
021    }
022      
023    publicString rReadConsole(Rengine re, String prompt, intaddToHistory) {
024        System.out.print(prompt);
025        try{
026            BufferedReader br=newBufferedReader(newInputStreamReader(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        returnnull;
033    }
034      
035    publicvoidrShowMessage(Rengine re, String message) {
036        System.out.println("rShowMessage \""+message+"\"");
037    }
038      
039    publicString rChooseFile(Rengine re, intnewFile) {
040    FileDialog fd =newFileDialog(newFrame(), (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    returnres;
046    }
047      
048    publicvoid  rFlushConsole (Rengine re) {
049    }
050      
051    publicvoid  rLoadHistory  (Rengine re, String filename) {
052    }           
053      
054    publicvoid  rSaveHistory  (Rengine re, String filename) {
055    }           
056}
057  
058publicclassRtest {
059    publicstaticvoidmain(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=newRengine(args, false,newTextConsole());
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                inti=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                inti = 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            booleanby[] = { 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                inti=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        longxp1 = re.rniPutString("hello");
141        re.rniAssign("a", xp1,0);
142  
143        // Example: how to create a named list or data.frame
144        doubleda[] = {1.2,2.3,4.5};
145        doubledb[] = {1.4,2.6,4.2};
146        longxp3 = re.rniPutDoubleArray(da);
147        longxp4 = re.rniPutDoubleArray(db);
148          
149        // now build a list (generic vector is how that's called in R)
150        longla[] = {xp3, xp4};
151        longxp5 = re.rniPutVector(la);
152  
153        // now let's add names
154        String sa[] = {"a","b"};
155        longxp2 = 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        longxp7 = re.rniPutStringArray(rn);
162        re.rniSetAttr(xp5,"row.names", xp7);
163          
164        longxp6 = 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            longe=re.rniParse("data(iris)",1);
173            System.out.println("Result = "+e+", running eval");
174            longr=re.rniEval(e, 0);
175            System.out.println("Result = "+r+", building REXP");
176            REXP x=newREXP(re, r);
177            System.out.println("REXP result = "+x);
178        }
179        {
180            System.out.println("Parsing");
181            longe=re.rniParse("iris",1);
182            System.out.println("Result = "+e+", running eval");
183            longr=re.rniEval(e, 0);
184            System.out.println("Result = "+r+", building REXP");
185            REXP x=newREXP(re, r);
186            System.out.println("REXP result = "+x);
187        }
188        {
189            System.out.println("Parsing");
190            longe=re.rniParse("names(iris)",1);
191            System.out.println("Result = "+e+", running eval");
192            longr=re.rniEval(e, 0);
193            System.out.println("Result = "+r+", building REXP");
194            REXP x=newREXP(re, r);
195            System.out.println("REXP result = "+x);
196            String s[]=x.asStringArray();
197            if(s!=null) {
198                inti=0;while(i<s.length) { System.out.println("["+i+"] \""+s[i]+"\""); i++; }
199            }
200        }
201        {
202            System.out.println("Parsing");
203            longe=re.rniParse("rnorm(10)",1);
204            System.out.println("Result = "+e+", running eval");
205            longr=re.rniEval(e, 0);
206            System.out.println("Result = "+r+", building REXP");
207            REXP x=newREXP(re, r);
208            System.out.println("REXP result = "+x);
209            doubled[]=x.asDoubleArray();
210            if(d!=null) {
211                inti=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            intd[]=x.asIntArray();
220            if(d!=null) {
221                inti=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}
view source
print?
1输出结果如下:
view source
print?
1<A id=ematt:138class=highslide href="/content/uploadfile/201208/f3ccdd27d2000e3f9255a7e3e2c4880020120804140622.jpg"target=_blank getParams="null"jQuery1346517118937="6"><IMG border=0alt=点击查看原图 src="/content/uploadfile/201208/thum-f3ccdd27d2000e3f9255a7e3e2c4880020120804140622.jpg"></A>

 

原创粉丝点击