我使用 Twitter anomaly detection algorithm在我的项目中。为此,我使用 Rserve 库在我的 Java 应用程序中运行 R 代码。
我的 Java 代码:
RConnection connection = new RConnection();
connection.voidEval("library(AnomalyDetection)");
connection.eval("res <- AnomalyDetectionTs(data.frame(/*list of timestamps*/,/*list of values*/), direction='both', plot=FALSE, longterm=TRUE)");
因此,我得到了这个输出:
$anoms
timestamp anoms
1 1980-09-25 16:05:00 21.3510
2 1980-09-29 06:40:00 193.1036
3 1980-09-29 21:44:00 148.1740
现在为了获得结果,我使用了这个不好的解决方案:
connection.eval("write.csv(res[['anoms']],file='anom.csv')");
然后我用 Java 打开这个文件并解析结果。
那么,如何使用Rserve possibilities for data.frame 结构在Java 中得到输出结果呢?
最佳答案
只需编写 R 命令,使其将所需结果返回给 Java:
RList l = c.eval("AnomalyDetectionTs(data, direction='both',
plot=FALSE, longterm=TRUE)$anoms").asList();
您得到的是带有两个变量 timestamp
和 anoms
的数据框(作为列表)。
但是,AnomalyDetectionTs
以非常烦人且效率低下的格式返回日期,因此您可能希望实际返回更合理的结果,这在 Java 中更容易处理,例如:
RList l = c.eval("{ res <- AnomalyDetectionTs(data, direction='both', plot=FALSE,
longterm=TRUE)$anoms;
list(as.POSIXct(res$timestamp), res$anoms) }").asList();
double ts[] = l.at(0).asDoubles();
double anom[] = l.at(1).asDoubles();
for (int i = 0; i < ts.length; i++)
System.out.println(new java.util.Date((long)(ts[i]*1000.0)) + ": " + anom[i]);
PS:Rserve 问题的正确位置是 stats-rosuda-devel mailing list这会更快地给你答案。
关于java - 如何使用 Rserve 在 Java 中获取 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34388513/