Running R script from C# program

   R script can be easily executed, and the result can be parsed by the C# program. Here I will show how to execute the R script from the C# program. An execution approach is simple. We run the R execution file (Rscript.exe) with a script as an argument by a Process class in C#. If the script requires additional arguments, they can also be included in a ProcessStartInfo object.
   In my new post, How to Run R Script from C# Program in a Session, I covered running R script from the C# application in an efficient way. Please check the above post too.
   We execute a below sample R source code through the C# program. In this source code, we get a prediction result for classification problems with a gbm function.


# Gradient Boosting model with gbm
# Turn off library warning messages
suppressWarnings(library(gbm))


# gbm result for simulated data
get_gbm <- function()
{
    set.seed(123)
    a <- sample(1:10, 250, replace = T)
    b <- sample(10:20, 250, replace = T)
    flag <- ifelse(a > 5 & b > 10, "red", ifelse(a < 3, "yellow", "green"))
    df <- data.frame(a = a, b = b, flag = as.factor(flag))

    train <- df[1:200,]
    test <- df[200:250,]

    mod_gb <- gbm(flag ~ a + b,
                  data = train,
                  distribution = "multinomial",
                  shrinkage = .01,
                  n.minobsinnode = 10,
                  n.trees = 100)

    pred <- predict.gbm(object = mod_gb,
                        newdata = test,
                        n.trees = 100,
                        type = "response")

    res <- cbind(test, pred)
    return(res)
}

# need to call function to get the output
get_gbm()


Save the script as 'gbm_test.R' file.
Next, we write a C# program to execute a gbm_test.R script.

using System;
using System.Diagnostics;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var rpath = @"C:\Program Files\R\R-3.4.3\bin\Rscript.exe";
        var scriptpath = @"D:\repos\rsource\gbm_test.R";
        var output = RunRScript(rpath, scriptpath);

        Console.WriteLine(output);
        Console.ReadLine();
    }

    private static string RunRScript(string rpath, string scriptpath)
    {
        try
        {
            var info = new ProcessStartInfo
            {
                FileName = rpath,
                WorkingDirectory = Path.GetDirectoryName(scriptpath),
                Arguments = scriptpath,
                RedirectStandardOutput = true,
                CreateNoWindow = true,
                UseShellExecute = false
            };

            using (var proc = new Process { StartInfo = info })
            {
                proc.Start();
                return proc.StandardOutput.ReadToEnd();
            }
        }
        catch (Exception ex)
        {         Console.WriteLine(ex.ToString());
        }
        return string.Empty;
    }
}

We compile C# code and run the program, the result looks as below.


I hope you have found this post useful. Thank you for reading!


13 comments:

  1. Thanks for sharing. Helped me a lot.

    ReplyDelete
  2. Hello,thanks for article, it is really helpful.
    However I do not get any output in the console. Do you have any idea ?

    ReplyDelete
    Replies
    1. You are welcome!
      1. Make sure your R script is working without error and returning the output. In example, we call the function to get the output.

      # need to call function to get the output
      get_gbm()

      2. Make sure your rpath and rsciptpath are correct in your C# code.

      Delete
    2. From me it ran from the command line and in r but wouldn't in c# app until i changed the Arguments parameter to Path.GetFileName(scriptpath)
      i.e
      var info = new ProcessStartInfo
      {
      FileName = rpath,
      WorkingDirectory = Path.GetDirectoryName(scriptpath),
      Arguments = Path.GetFileName(scriptpath),
      RedirectStandardOutput = true,
      CreateNoWindow = true,
      UseShellExecute = false
      };

      Delete
  3. Hello, It's working perfectly now. The issue was related to the location of my files. the R script and the C# one have to be in the same file.Thank you so much

    ReplyDelete
  4. Hello,
    I'm trying to run this with one of my R files but the output is blank. Do you have any ideas as to why this might be?
    Thank you.

    ReplyDelete
  5. Hi!
    Is there a way to get the ooutput from R Console as it is being written?
    thanks!

    ReplyDelete
  6. Hi,
    I tried this function with R script that write files.
    The files are not created and no errors appear.
    Any recommendations?

    ReplyDelete
  7. I think you have a small bug in your code here. It looks like you aren't calling the R script that you developed and named "gbm_test.R." I believe the following line in your code:

    var scriptpath = @"D:\repos\rsource\Script.R";

    Should have been written as:

    var scriptpath = @"D:\repos\rsource\gbm_test.R";

    ReplyDelete
  8. From visual studio it is working fine, however it is not working when i host in IIS, i am using .net core api

    ReplyDelete