Csharp/C#教程:以编程方式执行R传奇脚本共享


以编程方式执行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(@"SOFTWARER-core") ?? Registry.CurrentUser.OpenSubKey(@"SOFTWARER-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

上述就是C#学习教程:以编程方式执行R脚本分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  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 FilesRR-3.3.1binRScript.exe","C:\Users\lenovo\Desktop\R_trial\withoutALL.R"); } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/988034.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐