从java运行rscript并不显示任何结果

时间:2017-05-30 04:00:11

标签: java r rserve

我正在使用Rserve从java调用r脚本。程序运行并终止但不输出我想要的内容。在我的R脚本中,我有多个print语句,所以理论上当我的java程序运行时应该打印那些语句。但是我的java程序正在打印我的脚本路径而不是实际的r脚本内容。

我该怎么办?我怎么知道我的脚本是否正常运行?

R脚本:

library(Rserve)
Rserve()
print(323325)
print("Hellow world this is an R script")
print("R script ran successfully")
print("Running")

Java程序:

public static void main(String[] args) throws REXPMismatchException, REngineException{

        RConnection c = new RConnection();
        //REXP rengine = c.eval("R.version.string");
        //rengine = c.eval("source('./src/main/resources/Script/DB.R')");
        //System.out.println(rengine.asString());



        REXP rResponseObject = c.parseAndEval("try(eval('./src/main/resources/Script/DB.R'),silent=TRUE)");
        System.out.println(rResponseObject.asString());
        if (rResponseObject.inherits("try-error")) { 
            System.err.println("Error: " + rResponseObject.asString());
        }


    }

实际输出:

  

./的src /主/资源/脚本/ DB.R

期望的输出:

  

[1]“Hellow world这是一个R剧本”   [1]“R脚本成功运行”   [1]“跑步”

2 个答案:

答案 0 :(得分:0)

eval评估表达式。 './src/main/resources/Script/DB.R'是一个常量字符串,用于计算自身。

您可能想要的是source

答案 1 :(得分:0)

我解决了这个问题。我的r脚本现在正在运行并执行它应该执行的操作。

在我的r脚本文件中,我创建了一个函数并将我的整个r代码放在该函数中

在我的java程序中,我给出了我的r脚本的路径:

c.eval("source(\"DataPull.R\")");

然后我调用了我的r脚本的功能并检查了这样的错误:

REXP r = c.parseAndEval("try(eval(myAdd()),silent=TRUE)");
        if (r.inherits("try-error")) System.err.println("Error: "+r.asString());
            else System.out.println("Success eval 2");

并且有效。

这是我的java程序文件:

public static void main(String[] args) throws REXPMismatchException, REngineException, IOException{

        RConnection c = new RConnection();
        c.eval("source(\"DataPull.R\")");
        REXP r = c.parseAndEval("try(eval(myAdd()),silent=TRUE)");
        if (r.inherits("try-error")) System.err.println("Error: "+r.asString());
            else System.out.println("Success eval 2");  
    }

这是我的r脚本文件:

myAdd <- function(){
  library(Rserve)
  Rserve()
  print(323325)
  print("Hellow world this is an R script")
  print("R script ran successfully")
  print("Running")   
}