How to get data.frame in Java using rserve

I am using Twitter anomaly detection algorithm in my project. To do this, I use the Rserve library to run R code in my Java application.

My Java code is:

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)");

And, as a result, I got this conclusion:

    $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

To get the results, I use this not a pleasant solution: connection.eval("write.csv(res[['anoms']],file='anom.csv')");

Then I will open this file in Java and analyze the results.

So how to get output in Java using the Rserve features for the data.frame structure?

+4
source share
1 answer

Just write the R command to return the desired result back to 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 , .

+4

Source: https://habr.com/ru/post/1621045/


All Articles