如何使用Rserve将文件路径传递给在Java中调用的Rscript?

时间:2021-04-08 10:00:13

I am using Rserve to access an R script through my Java project. The java code asks for a user input to enter the file location and stores in a String variable. This variable is then passes through to the R function which should read the file location. But doing this I get the following error:

我正在使用Rserve通过我的Java项目访问R脚本。 java代码要求用户输入以输入文件位置并存储在String变量中。然后,该变量将传递给应该读取文件位置的R函数。但这样做我得到以下错误:

Exception in thread "main" org.rosuda.REngine.Rserve.RserveException: eval failed, request status: error code: 127
at org.rosuda.REngine.Rserve.RConnection.eval(RConnection.java:234)
at testMain.main(testMain.java:23)

Here is my java code:

这是我的java代码:

import java.util.Scanner;

import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;

public class testMain {
    static String dirPath;
    public static void main(String[] args) throws REXPMismatchException, REngineException         
{

        // For user input
        Scanner scanner = new Scanner(System.in );
        System.out.println("Enter the file path: ");

        dirPath = scanner.nextLine();

        RConnection c = new RConnection();
        // source the Palindrome function
        c.eval("source('/home/workspace/TestR/testMain.R')");

        REXP valueReturned = c.eval("testMain(dirPath)");
       System.out.println(valueReturned.asString());
    }
}

Here is my R function:

这是我的R功能:

testMain <- function(dirPath)
{
     p<-dirPath
     return(p)
}

Can someone please help me how to solve this?

有人可以帮我解决这个问题吗?

1 个解决方案

#1


1  

Probably something like this would work:

可能这样的东西会起作用:

REXP valueReturned = c.eval("testMain(\""+dirPath+"\")");

The problem is -I think-, that you have not set the dirPath variable for the R context before referencing it.

问题是 - 我认为 - 在引用它之前你没有为R上下文设置dirPath变量。

#1


1  

Probably something like this would work:

可能这样的东西会起作用:

REXP valueReturned = c.eval("testMain(\""+dirPath+"\")");

The problem is -I think-, that you have not set the dirPath variable for the R context before referencing it.

问题是 - 我认为 - 在引用它之前你没有为R上下文设置dirPath变量。