使用终端将参数传递给Rserve

时间:2017-01-11 06:48:29

标签: r rserve

我有一个R代码,它有一个训练有素的机器学习模型。现在我想预测新数据。

当前方法:

Script code.R '[{"x1" : "1011", "x2" : "1031", "x4" : "0.65"}]'

我会得到答案,问题是加载和设置环境需要花费太多时间

代码:

# Loading the library

suppressPackageStartupMessages(library(C50))
suppressPackageStartupMessages(library(jsonlite))
suppressPackageStartupMessages(library(plyr))

# Loading the trained model

model1 <- readRDS("model1.RDA")

 x <- (args[1])

# Function which wraps prediction and son handling

output <- function(x) {

df <- fromJSON(x)

df[is.na(df)] <- 0

prediction <- predict.C5.0(model1, newdata = df, type = "class")

json_df <- toJSON(prediction)

return(json_df)
}

 output(x)

问题:

  • 我想使用Rserve并将参数传递给此,我无法使用 弄明白怎么样?我应该做些什么修改?

  • 我知道要添加库(Rserve),然后执行 run.Rserve()但超出 我不知道怎么做?

2 个答案:

答案 0 :(得分:1)

所以我使用NodeJS与Rserve交谈。

首先从终端安装节点和npm。

npm install --save rserve-client

javascript文件中的代码为:

var r = require('rserve-client');
r.connect('localhost', 6311, function(err, client) {
    client.evaluate('a<-2.7+2', function(err, ans) {
        console.log(ans);
        client.end();
    });
});
  • 观察节点正在使用端口'6311'(Rserve的默认值)

  • 部分'a&lt; -2.7 + 2'是发送给R的内容,修改此部分

答案 1 :(得分:1)

如果您想使用Java客户端,则需要下载REngine jars,以下代码将有所帮助(我正在使用Java):

import org.rosuda.REngine.*;
import org.rosuda.REngine.Rserve.*;
import java.util.Arrays;

public class RServeCommunication {

    public static void main(String[] args) {
      try {
        // Setup the connection with RServer through RServe
        RConnection rConnection = new RConnection("127.0.0.1", 6311); 
        // Call R function 
        REXP retValues = rConnection.eval("rnorm(10)");
        // print the values returned to console
        System.out.println(Arrays.toString(retValues.asDoubles()));
        // [1.4280800442888217, -0.11989685521338722, 0.6836180891125788, 0.7913069852336285, -0.8968664915403061, 0.0681405000990237, -0.08726481416189025, -0.5322959519563994, -0.3302662744787598, 0.45030516965234024]

      }
      catch (REngineException e) {
        System.out.println("Error: " + e.toString());
      }
      catch (REXPMismatchException e) {
        System.out.println("Error: " + e.toString());
      }
    } 
}