簡體   English   中英

使用 RScript.exe 運行帶參數的 rscript

[英]Using RScript.exe to run a rscript with parameter

我有一個簡單的 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 文件中獲取輸出。

我嘗試了以下線程中提供的幾種方法

傳遞命令

如何從 R 腳本中讀取命令行參數?

在 .net 中使用 start.process 運行 R 腳本

但是我無法得到我想要的。 腳本沒有被執行。 我還嘗試在我的 rscript 中添加 args<-commandArgs(TRUE) 但它不起作用。

基本上,我是一名 .net 開發人員,由於某些客戶端需要,我希望從我的 Web 應用程序運行 r 腳本。 我對 R 不太了解,如果有人幫助我了解如何將參數值傳遞給我的 r 代碼,這對我會有幫助。

我找到了一種通過 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 代碼並將參數傳遞給我的logistics.R 代碼。

創建包裝器后,我將使用以下代碼執行我的 r 代碼

Rscript logistic-wrapper.R 3.2 0.5

執行logistic-wrapper.R 以及參數3.2 和0.5 將執行我的logistic.r 代碼提供的參數。

最快的方法是使用 args 運行 R CMD 批處理並將結果寫入文件,讓我們從命令行說 .json:R CMD BATCH --slave '--args ab c'

在 R:

args <- commandArgs(trailingOnly = TRUE)
a <- args[1]
b <- args[2]
c <- args[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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM