【问题标题】:Using RScript.exe to run a rscript with parameter使用 RScript.exe 运行带参数的 rscript
【发布时间】:2016-01-17 18:08:09
【问题描述】:

我有一个简单的 R 脚本,它接受输入值并根据输入值进行一些计算并将其写入 csv 文件。下面是我的 r 脚本的代码。

testfun=function(x){
  x<-args[1]
  x=sqrt(x)+(x*x)
  a=x+x+x
  b=data.frame(x,a)
  setwd("D:\\R Script")
  write.csv(b,"testfun.csv",row.names=F)
}

我使用 Jake Drew 提供的 Rscriptrunner 从我的 asp.net Web 应用程序调用此 rscript

/// <summary>
/// This class runs R code from a file using the console.
/// </summary>
public class RScriptRunner
{
    /// <summary>
    /// Runs an R script from a file using Rscript.exe.
    /// Example:  
    ///   RScriptRunner.RunFromCmd(curDirectory + @"\ImageClustering.r", "rscript.exe", curDirectory.Replace('\\','/'));
    /// Getting args passed from C# using R:
    ///   args = commandArgs(trailingOnly = TRUE)
    ///   print(args[1]);
    /// </summary>
    /// <param name="rCodeFilePath">File where your R code is located.</param>
    /// <param name="rScriptExecutablePath">Usually only requires "rscript.exe"</param>
    /// <param name="args">Multiple R args can be seperated by spaces.</param>
    /// <returns>Returns a string with the R responses.</returns>
    public static string RunFromCmd(string rCodeFilePath, string rScriptExecutablePath, string args, int iInput)
    {
            string file = rCodeFilePath;
            string result = string.Empty;

            try
            {

                var info = new ProcessStartInfo();
                info.FileName = rScriptExecutablePath;
                info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath);
                info.Arguments = rCodeFilePath + " " + args;

                info.RedirectStandardInput = false;
                info.RedirectStandardOutput = true;
                info.UseShellExecute = false;
                info.CreateNoWindow = true;

                using (var proc = new Process())
                {
                    proc.StartInfo = info;
                    proc.Start();
                    result = proc.StandardOutput.ReadToEnd();
                    proc.Close();
                }

                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("R Script failed: " + result, ex);
            }
    }
}

我调用脚本到 rscriptrunner 的方式如下

int x = 64;

    string scriptPath = string.Format(@"C:\Program Files\R\{0}\bin\Rscript.exe", Rversion);
    string path = string.Format(@"D:\testfun.r");
    string result = RScriptRunner.RunFromCmd(path, scriptPath, path.Replace('\\', '/'), x);

基本上我想将我的 Web 应用程序中的 x 值提供到我的 r 代码中,并在 r 脚本中指定的 csv 文件中获取输出。

我尝试了以下线程中提供的几种方法

Passing Command

How can I read command line parameters from an R script?

Run R script with start.process in .net

但是我无法得到我想要的。脚本没有被执行。 我还尝试在我的 rscript 中添加 args

基本上,我是一名 .net 开发人员,由于某些客户需要,我想从我的 Web 应用程序运行 r 脚本。我不太了解 R,如果有人帮助我了解如何将参数值传递给我的 r 代码,那对我会有帮助。

【问题讨论】:

  • 这是你的整个 R 代码吗?您正在定义函数但从不使用它。
  • 是的。执行上述代码后,该函数将被称为 testfun(x value)。

标签: asp.net r


【解决方案1】:

我找到了一种通过 ASP.NET C# 为我的函数提供参数的方法。

基本上我为我的 r 代码创建了一个包装器,这样我就可以从另一个 wrapper.r 代码中调用我真正的 r 代码,并在其中传递我的参数。

包装代码如下所示

args <- commandArgs(TRUE)
r <- as.double(args[1])
x <- as.double(args[2])
source("logistic.R")
logistic(r, x) 

在这里,我使用源函数调用我的真实 r 代码并将参数传递给我的logistic.R 代码。

创建包装器后,我将使用以下代码执行我的 r 代码

Rscript logistic-wrapper.R 3.2 0.5

与参数 3.2 和 0.5 一起执行logistic-wrapper.R 将执行随参数提供的我的logistic.r 代码。

【讨论】:

  • 我现在正在构建同样的东西,但我发现你的代码有点混乱。例如,您将 rscript 的路径传递了两次,它就变成了一个参数。你到底在哪里调用 Rscriptlogistic-wrapper.R 3.2 0.5?请帮帮我
【解决方案2】:

最快的方法是使用 args 运行 R CMD 批处理并将结果写入文件,比如说 .json 从命令行: R CMD BATCH --slave '--args a b c'

在R中:

args <- commandArgs(trailingOnly = TRUE)
a <- args[1]
b <- args[2]
c <- args[3]

只需将结果写入文件

【讨论】:

    【解决方案3】:

    你可以使用 funr 包。

    假设你的脚本是这样的

    # define the function
    testfun <- function(x = 2, outfile = "testfun.csv"){
      x=sqrt(x)+(x*x)
      a=x+x+x
      b=data.frame(x, a)
      #setwd("D:\\R Script")
      write.csv(b,outfile,row.names=F)
    }
    
    help_text = "
    This script creates a data.frame and writes it out as a CSV file.
    
    Usage: testfunr.R testfun x=<a number> outfile=<myfile.csv>
    "
    
    library(funr)
    out = funr(commandArgs(trailingOnly = TRUE), help_text = help_text)
    

    然后简单地用参数调用你的函数。

    Rscript testfun.r testfun x=2
    # one may explicitly provide the output filename as well
    Rscript testfun.r testfun x=2 outfile=myfile.csv
    

    【讨论】:

    • 嗨尝试了您的解决方案,但没有获得 testfun.csv 文件。我尝试在 r studio 中运行代码,但在 x
    • 你可以试试这个,我照原样复制了你的函数,没想到有问题。
    猜你喜欢
    • 2015-05-20
    • 2019-10-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    相关资源
    最近更新 更多