以编程方式执行R脚本

我有一个C#程序生成一些R代码。 现在我将脚本保存到文件,然后将其复制/粘贴到R控制台。 我知道有一个到R的COM接口,但它似乎不适用于最新版本的R(或2.7.8之后的任何版本)。 有什么方法可以在将其保存到文件后以编程方式从C#执行R脚本?

要在C#执行此操作,您需要使用

 shell (R CMD BATCH myRprogram.R) 

一定要像这样包裹你的情节

 pdf(file="myoutput.pdf") plot (x,y) dev.off() 

或图像包装

这是我最近为此目的写的课程。 您还可以从C#和R传入并返回参数:

 ///  /// This class runs R code from a file using the console. ///  public class RScriptRunner { ///  /// 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]); ///  /// File where your R code is located. /// Usually only requires "rscript.exe" /// 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); } } } 

注意:如果您对清理过程感兴趣,可能需要在代码中添加以下内容。

proc.CloseMainWindow(); proc.Close();

我认为C#有一个类似于system()的函数,它允许你调用通过Rscript.exe运行的脚本。

我们的解决方案基于stackoverflow上的这个答案从.net调用R(编程语言)

随着monor更改,我们从字符串发送R代码并将其保存到临时文件,因为用户在需要时运行自定义R代码。

 public static void RunFromCmd(string batch, params string[] args) { // Not required. But our R scripts use allmost all CPU resources if run multiple instances lock (typeof(REngineRunner)) { string file = string.Empty; string result = string.Empty; try { // Save R code to temp file file = TempFileHelper.CreateTmpFile(); using (var streamWriter = new StreamWriter(new FileStream(file, FileMode.Open, FileAccess.Write))) { streamWriter.Write(batch); } // Get path to R var rCore = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\R-core") ?? Registry.CurrentUser.OpenSubKey(@"SOFTWARE\R-core"); var is64Bit = Environment.Is64BitProcess; if (rCore != null) { var r = rCore.OpenSubKey(is64Bit ? "R64" : "R"); var installPath = (string)r.GetValue("InstallPath"); var binPath = Path.Combine(installPath, "bin"); binPath = Path.Combine(binPath, is64Bit ? "x64" : "i386"); binPath = Path.Combine(binPath, "Rscript"); string strCmdLine = @"/c """ + binPath + @""" " + file; if (args.Any()) { strCmdLine += " " + string.Join(" ", args); } var info = new ProcessStartInfo("cmd", strCmdLine); 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(); } } else { result += "R-Core not found in registry"; } Console.WriteLine(result); } catch (Exception ex) { throw new Exception("R failed to compute. Output: " + result, ex); } finally { if (!string.IsNullOrWhiteSpace(file)) { TempFileHelper.DeleteTmpFile(file, false); } } } } 

完整的博客文章: http : //kostylizm.blogspot.ru/2014/05/run-r-code-from-c-sharp.html

这是实现这一目标的简单方法,

我的Rscript位于:

C:\ Program Files \ R \ R-3.3.1 \ bin \ RScript.exe

R代码位于:

C:\用户\联想\桌面\ R_trial \ withoutALL.R

  using System; using System.Diagnostics; public partial class Rscript_runner : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { Process.Start(@"C:\Program Files\R\R-3.3.1\bin\RScript.exe","C:\\Users\\lenovo\\Desktop\\R_trial\\withoutALL.R"); } }