我想知道是否有可能在传递值列表的同时运行R脚本,并输出结果值列表回到C#。我看到有人说R.NET很好,但我只看到使用它直接创建值、操纵值、访问值等示例,而我想要做的是运行已经创建的脚本,将数据输入进去处理后返回数据。我也知道我可以使用CSV文件来实现这一点,但重点是我想省略中间环节。
R
脚本来进行说明。Create a text file as name.r
, with your r code, something like below. I named it as 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)
接下来创建一个C#类(可以随意命名,我称其为RScriptRunner
),如下所示,也可在这里找到。 这是一个简单的类,只调用一个过程(一个exe文件)。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for RScriptRunner
/// </summary>
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
)的位置。