R脚本formsC#。 传递参数,运行脚本,检索结果

我想知道是否可以在传递值列表时运行Rscript,让R脚本运行,然后将重新分配的值列表输出回c#。

我见过人们说R.N​​ET很好但是我只看到过使用它直接创建值,操作它们,访问它们等等的例子,当我想要做的是运行已经创建的脚本来接收数据时,处理它并返回数据。 我也知道我可以用csv文件做到这一点但重点是我想切出中间人。

这个问题大约有5年了,这里有一些答案可供选择。 我将使用一个非常简单的R脚本来完成它。

最好从这个链接开始

在这个简单的例子中,我将3传递给R,用5添加它并得到结果(8)。

脚步

  1. 使用您的r代码创建一个文本文件name.r ,如下所示。 我把它命名为rcodeTest.r

     library(RODBC) # you can write the results to a database by using this library args = commandArgs(trailingOnly = TRUE) # allows R to get parameters cat(as.numeric(args[1])+5)# converts 3 to a number (numeric) 

然后创建ac RScriptRunner (称之为任何东西,我称之为RScriptRunner ),如下所示,也可以在这里找到 。 这是一个简单的类,只调用一个过程(一个exe文件)

  using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Web; ///  /// Summary description for RScriptRunner ///  public class RScriptRunner { public RScriptRunner() { // // TODO: Add constructor logic here // } // 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]); /// /// /// rCodeFilePath - File where your R code is located. /// rScriptExecutablePath - Usually only requires "rscript.exe" /// args - Multiple R args can be seperated by spaces. /// Returns - a string with the R responses. public static string RunFromCmd(string rCodeFilePath, string rScriptExecutablePath, string args) { 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(); } return result; } catch (Exception ex) { throw new Exception("R Script failed: " + result, ex); } } } 

然后调用并传递参数

  result = RScriptRunner.RunFromCmd(path + @"\rcodeTest.r", @"D:\Programms\R-3.3.3\bin\rscript.exe", "3"); 

rscript.exe位于您的R目录中, path是您的r脚本的位置( rcodeTest.r

现在您可以将结果8 = 5 + 3作为输出,如下所示。 在此处输入图像描述