2

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" + "C:\test.R"
process.start("CMD.exe", strCmd

apparently this should work but in my case the cmd pops up (lokated in my debug folder) and nothing happens.

Another way i tried was

process.start("Rgui.exe", "C:\test.R")

Error Message: Argument "C:\test.R" ignored

this is not working either.

for my r script i just used an example

sink()
setwd("C:/")
x <- data.frame(a = I("a \" quote"), b = pi)
sink(test.csv)
ruedi
  • 5,365
  • 15
  • 52
  • 88
  • Does this result in strCmd being "R CMD BATCHC:\test.R"? – IRTFM Aug 14 '13 at 06:29
  • ah ok that is helpful. i changed it to "strCmd = "R CMD BATCH" + " " + "C:/test.R". The cmd opens and closes without error but no test.csv is created. Do you have an idea why this is not happening? – ruedi Aug 14 '13 at 06:37
  • Did you mean to type `sink("test.csv")`? And perhaps close that file with `sink()`? – IRTFM Aug 14 '13 at 06:39
  • I did the changes but still dont get an outputfile. – ruedi Aug 14 '13 at 06:47
  • If you didn't get the output you expected, then you should look for error messages in `test.r.Rout`. It should look like a transcript of a console session. – IRTFM Aug 14 '13 at 06:59

2 Answers2

6

this is how it works for me:

        Dim myprocess As New Process
        myprocess.StartInfo = New ProcessStartInfo("C:\Program Files (x86)\R\R-2.6.2\bin\R.exe", "CMD BATCH C:/Users/test/test3.R C:/Users/test/testout.csv")
        myprocess.Start()

second approach (first app. doesnt give me a good csv output so here this is a workaround):

    Dim proc = New Process
    proc.StartInfo.FileName = "C:\Program Files (x86)\R\R-2.6.2\bin\Rscript.exe"
    proc.StartInfo.WorkingDirectory = "C:\Program Files (x86)\R\R-2.6.2\bin"
    proc.StartInfo.Arguments = "C:/Users/Desktop/RtoVB/test4.r"
    proc.StartInfo.UseShellExecute = True
    proc.StartInfo.RedirectStandardOutput = False
    proc.Start()
ruedi
  • 5,365
  • 15
  • 52
  • 88
  • Instead of R CMD BATCH, you can use Rscript.exe which is intended for running script files. Also, version 2.6.2 is way old now. – Hong Ooi Aug 14 '13 at 07:28
  • I tried "myprocess.StartInfo = New ProcessStartInfo("C:\Program Files (x86)\R\R-2.6.2\bin\Rscript.exe", C:/Users/test/test3.R C:/Users/test/testout.csv")" instead but this is not working, no error, no outputfile was created. How can i accomplish this with the rscript.exe? – ruedi Aug 14 '13 at 14:24
  • @Jake Where is GetDirectoryName defined? I get error at GetDirectoryName(rScriptExecutablePath). Since I am new to both C# and R I have trouble fixing the error. – Sunny Aug 19 '15 at 21:07
5

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

                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("R Script failed: " + result, ex);
            }
    }
}
Jake Drew
  • 2,230
  • 23
  • 29
  • Hi! I got it to work with 'MyR.RunRScript("C:\myRScript.R", "C:\Rscript.exe", "9999 4 5 66 string")' but I dont get the result working. No matter what I try MsgBox(result) is always empty. Do you know why or if I do something wrong? – ruedi Nov 17 '14 at 13:03
  • I am able to get the result as follows: – Jake Drew Nov 18 '14 at 20:49
  • string scriptPath = @"C:\Users\Jake\Desktop\RunR\rscript.txt"; string result = RScriptRunner.RunFromCmd(scriptPath, "rscript.exe", ""); Console.WriteLine(result); Console.ReadKey(); – Jake Drew Nov 18 '14 at 20:49
  • However, result is only going to capture what data R returns to the R console. If you want results for a file, you will have issue commands in R to write your data to the file. – Jake Drew Nov 18 '14 at 20:50
  • For instance, this would return data to "result" in R: test <- 1:100 test – Jake Drew Nov 18 '14 at 20:51
  • The first line will do nothing, but adding "test" in R prints the values of test to the R console. Hope that makes sense. – Jake Drew Nov 18 '14 at 20:51