我正在使用RServe((并尝试将数组列表从java传递到R。我收到一个错误,包括程序代码和我给出的错误。
String vector = "c(1,2,3,4)";
connR.eval("meanVal=mean(" + vector + ")");
double mean = connR.eval("meanVal").asDouble();
System.out.println("The mean of given vector is=" + mean);
ArrayList fDataset = (ArrayList)f.FDataset;
connR.eval("library(forecast)");
connR.eval("library(tseries)");
System.out.println(fDataset.toString());
connR.assign("myData",fDataset.toString());
System.out.println("*************myData ******************");
System.out.println(connR.eval("myData"));
connR.eval("timeSeries <- ts(myData,start=1,frequency=7)");
System.out.println("this is time series object : " + connR.eval("timeSeries"));
connR.eval("fitModel <- auto.arima(timeSeries)");
REXP fc = connR.eval("forecast(fitModel, n=3)");
System.out.println("this is the forecast output values: " + fc);
我得到的输出为
The mean of given vector is=2.5
[0, 0, 2, 1, 2, 10, 21, 0, 0, 3, 6, 5, 11, 51, 0, 11, 8, 6, 24, 25, 104, 0, 0, 6, 4, 5, 25, 71]
*************myData ******************
org.rosuda.REngine.REXPString@3c873c87[1]
this is time series object : org.rosuda.REngine.REXPString@4e774e77+[1]
org.rosuda.REngine.Rserve.RserveException: eval failed, request status:
error code: 127
at org.rosuda.REngine.Rserve.RConnection.eval(RConnection.java:234)
at forecast.ForecastAction.calculateForecast1(ForecastAction.java:323)
at forecast.ForecastAction.action(ForecastAction.java:140)
at forecast.ForecastAction.runApp(ForecastAction.java:83)
at forecast.ForecastAction.main(ForecastAction.java:36)
错误在行
connR.eval("fitModel <- auto.arima(timeSeries)");
由于另一行的错误,您在auto.arima
时出错。特别:
connR.assign("myData",fDataset.toString());
为myData
变量分配字符串值。因此,分配后的所有内容都是毫无意义的,timeSeries
只需用一个character
点创建它。
用.assign(Symbol symbol, double[] d)
做一个适当的作业,它会起作用。
我已经更改了代码,现在它可以工作了。我不确定您拥有的f
变量是什么,您只需要在使用 RServe 分配它之前将ArrayList
转换为double[]
。
RConnection c = new RConnection();
double[] list = {0, 0, 2, 1, 2, 10, 21, 0, 0, 3, 6, 5, 11, 51, 0, 11, 8, 6, 24, 25, 104, 0, 0, 6, 4, 5, 25, 71};
c.eval("library(forecast)");
c.eval("library(tseries)");
c.assign("myData", list);
c.eval("timeSeries <- ts(myData,start=1,frequency=7)");
c.eval("fitModel <- auto.arima(timeSeries)");
REXP fc = c.eval("forecast(fitModel, n=3)");
double[] res = fc.asList().at("mean").asDoubles();
System.out.println("this is the forecast output values: " + Arrays.toString(res));
c.close();
// this is the forecast output values: [0.0, 0.0, 6.0, 4.0, 5.0, 25.0, 71.0, 0.0, 0.0, 6.0, 4.0, 5.0, 25.0, 71.0]