Run R script with start.process in .net

前端 未结 2 399
生来不讨喜
生来不讨喜 2020-12-06 03:38

I want to run an r script in vb.net which saves data in a .csv file. Till now i found the following approaches:

dim strCmd as String
strCmd = \"R CMD BATCH\"         


        
2条回答
  •  佛祖请我去吃肉
    2020-12-06 04:28

    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();
                        proc.Close();
                    }
    
                    return result;
                }
                catch (Exception ex)
                {
                    throw new Exception("R Script failed: " + result, ex);
                }
        }
    }
    

提交回复
热议问题