c# - 以编程方式执行 R 脚本

标签 c# r com

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

最佳答案

这是我最近为此编写的类(class)。您还可以从 C# 和 R 传入和返回参数:

/// <summary>
/// This class runs R code from a file using the console.
/// </summary>
public class RScriptRunner
{
    /// <summary>
    /// 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]);
    /// </summary>
    /// <param name="rCodeFilePath">File where your R code is located.</param>
    /// <param name="rScriptExecutablePath">Usually only requires "rscript.exe"</param>
    /// <param name="args">Multiple R args can be seperated by spaces.</param>
    /// <returns>Returns a string with the R responses.</returns>
    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# - 以编程方式执行 R 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4485943/

相关文章:

C# 无法将类型 'System.Double' 的对象转换为类型 'System.Single'

c# - 如何在 MVC 中将 ObjectResult 转换为存储过程的 List 对象?

c# - 使用c#获取word消息框内容

r - ggpubr的compare_means和base R的pairwise.t.test给出了不同的结果

exception - ole32.dll 导致 GPF。如何解读DebugDiag报告?

c# - IdentityServer4 ASP.NET Core Identity 不会重定向回客户端

r - 在 R 中使用 by() 对 data.frame 进行二项式测试

使用多个分割字符时删除字符串的特定部分

windows - 进程外 COM 服务器卡住

visual-studio - 是否有有关.rgs文件语法的文档?