我想知道是否可以在传递值列表时运行Rscript,运行该R脚本然后将重新分配的值列表输出回c#.
我见过人们说R.NET很好但是我只看到过使用它直接创建值,操作它们,访问它们等等的例子,当我想要做的是运行已经创建的脚本来接收数据时,处理它并返回数据.我也知道我可以用csv文件做到这一点,但重点是我想切出中间人.
这个问题是关于5岁,另外还有一些适用于此类似的答案在这里。我将通过一个非常简单的R脚本来完成它。
最好从这个链接开始
在这个简单的示例中,我将 3 传递给 R,将其与 5 相加并返回结果 (8)。
脚步
name.r使用您的 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)
Run Code Online (Sandbox Code Playgroud)然后创建 ac# 类(称之为任何东西,我称之为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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后调用并传递参数,如
result = RScriptRunner.RunFromCmd(path + @"\rcodeTest.r", @"D:\Programms\R-3.3.3\bin\rscript.exe", "3");
Run Code Online (Sandbox Code Playgroud)
rscript.exe位于您的 R 目录中,并且path是您的 r 脚本 ( rcodeTest.r)
| 归档时间: |
|
| 查看次数: |
2098 次 |
| 最近记录: |