Executing R script programmatically

后端 未结 5 857
臣服心动
臣服心动 2020-12-09 18:31

I have a C# program that generates some R code. Right now I save the script to file and then copy/paste it into the R console. I know there is a COM interface to R, but it d

5条回答
  •  醉话见心
    2020-12-09 19:02

    Here is the class I recently wrote for this purpose. You can also pass in and return arguments from C# and 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);
                }
        }
    }
    

    NOTE: You may want to add the following to you code, if you are interested in cleaning up the process.

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

提交回复
热议问题