2013-06-12 60 views
1

我正在使用Java,我需要使用附加R庫並使用該庫中的函數。我試圖在以下幾個問題如何將附加R庫加載到JRI中並從Java執行?

How I can load a R script into JRI and execute from Java?

Problem loading R own created libraries in Java/JRI code

,但我仍然得到一個NullPointerException提供的答案。任何人都可以指出錯誤。三江源

這裏是我使用的代碼:

import org.rosuda.JRI.REXP; 
import org.rosuda.JRI.RVector; 
import org.rosuda.JRI.Rengine; 

public class RConnect { 

public void processFiles(String[] spectrumData) 
{ 
    // new R-engine 
    Rengine re=new Rengine (new String [] {"--vanilla"}, false, null); 
    if (!re.waitForR()) 
    { 
     System.out.println ("Unable to load R"); 
     return; 
    } 
    else 
     System.out.println ("Connected to R"); 

    REXP rexpSetFolder = re.eval("setwd('/home/user/R/x86_64-pc-linux-gnu-library/3.0')"); 
    REXP rexpFolder = re.eval("getwd()"); 
    System.out.println(rexpFolder.asString()); 

    REXP rexpLoad = re.eval("library(PROcess)"); 
    RVector f1 = (re.eval("read.files(spectrumData)").asVector()); 
    System.out.println(f1); 

    re.end(); 
} 
} 

回答

1

我試圖尋找的R封裝「過程」你剛纔提到的,但我沒有找到它,所以我不能測試你的代碼,但一般加入包做工完美的JRI,這裏是(使用套餐「預測」和「plyr」)的例子:

import org.rosuda.JRI.REXP; 
import org.rosuda.JRI.RVector; 
import org.rosuda.JRI.Rengine; 
/** 
* 
* @author yschellekens 
*/ 
public class StackOverfolw { 
    private static double[] foreCast; 
    private static int i; 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     // new R-engine 
    Rengine re=new Rengine (new String [] {"--vanilla"}, false, null); 
    if (!re.waitForR()) 
    { 
     System.out.println ("Unable to load R"); 
     return; 
    } 
    else 
     System.out.println ("Connected to R"); 

    re.eval("load(file='C:/Users/yschellekens.INTRANET/Desktop/java projects/count_basic.Rda') ", false); 
     re.eval("library(plyr)"); 
     re.eval("library(forecast)"); 
     re.eval("count_basic<-arrange(count_basic,TKDate)"); 
     re.eval("ts1<-ts(count_basic$click_count,frequency=7)");   
     re.eval("value<-stl(x=ts1,s.window=7)"); 
     re.eval("fit <- auto.arima(ts1)"); 
     re.eval("fit2<-forecast(fit,h=30)"); 
     re.eval("value3<-as.numeric(fit2$mean)"); 
     REXP testYvalue = re.eval("c(as.numeric(fit2$fitted),as.numeric(fit2$mean))"); 
     foreCast=testYvalue.asDoubleArray(); 


     for (i = 0; i < 10 ; i++) { 
      System.out.println(foreCast[i]);;} 
    re.end(); 
} 
    } 
  1. 現在看控制檯:

    運行: 相接R 524.0 597.0 530.0 440.0 406.0 435.0 479.0 523.0 580.0 574.0 BUILD SUCCESSFUL(總時間:4秒)

我猜我說你在早期版本的R(不是3.0)上下載了「PROcess」(我找不到),如果是這種情況,只需將該軟件包重新加載到R 3.0文件夾中即可。

+0

我試圖做類似的事情,它會拋出NPE。我爲它創建了一個[問題](http://stackoverflow.com/questions/38660138/rengine-eval-returns-null),請你看一下嗎? –