R语言node.js通信--实战

来源:互联网 发布:淘宝小也家是正品吗 编辑:程序博客网 时间:2024/05/29 15:08

项目源代码
https://github.com/harryluo163/rio-node-examples

这个一个node.js 通过Rserve 实现node.js与R的互通的例子 包含使用R语法调用和直接调用文件两种 本来是直接在web页面展示数据 现在大家直接切换到Cd C:\项目\R语言\examples 到这个目录中 然后使用命令 node t1 node t2 node t3 调用 后续在加吧。

另外需要1.安装R语言 2.安装Rserve 3.启动R服务端 同样支持远程调用
具体过程看上一篇
首先看t1.js
这里写图片描述

var rio = require("rio");rio.enableDebug(true);//开启调试模式rio.e({    command: "rnorm(20)",    host : "127.0.0.1",//服务器IP地址    port : 6311,});

执行

node t1

t1 是通过Rserves 调取本地127.0.0.1 端口6311的R语言服务

这里写图片描述

t2是调取本地的R文件

var rio = require("rio");var path = require("path");var r_file_command =  path.join(__dirname, "../routes/dump/uniqueSort.R");var args = {"test": [1,4,4,1,1,0,0,1,1,1,1,0,1,0,2,0,1,1,2,0,0,3,2]};function displayResponse(err, res) {    if (!err) {        res = JSON.parse(res);        console.log("result is " + res.test);    } else {        console.log("Optimization failed");    }}//rio.enableDebug(true);//开启调试模式rio.e({    filename: r_file_command,//加载R源    entrypoint: "uniqueSort",//R中的函数    data: args,//Nodejs传入R的参数    callback: displayResponse});

R文件

require(RJSONIO)uniqueSort <- function(test){  test <- fromJSON(test)  test <- unlist(test$test)  test <- unique(test)  test <- sort(test)  res <- list(test=test)  toJSON(res)}# args <- '{"test":[1,4,4,1,1,0,0,1,1,1,1,0,1,0,2,0,1,1,2,0,0,3,2]}'# res <- uniqueSort(args)# fromJSON(res)$test

然后其他T3 T4

var rio = require("rio");rio.e({command: "pi / 2 * 2"});rio.e({command: "c(1, 2)"});rio.e({command: "as.character('Hello World')"});rio.e({command: "c('a', 'b')"});rio.e({command: "Sys.sleep(5); 11"})
var rio = require("rio");var path = require("path");function displayResponse(err, res) {    if (!err) {        res = JSON.parse(res);        console.log(unescape(res.hello)); // Hello 'world'!    } else {        console.log(err, "Rserve call failed");    }}rio.e({    filename: path.join(__dirname, "../routes/dump/4.R"),    entrypoint: "run",    data: {        "hello": escape("Hello 'world'!")    },    callback: displayResponse});
原创粉丝点击