1

I have the following R script and C# program that is used as an example of calling R from C#. If I run the script from within R-GUI, I see the expected output. However, if I run it from within C# as below, I get no output. I tried moving the R script inside the C# executable directory, and this doesn't work either. I tried running Visual Studio as Administrator, again no output.

Not sure what I am doing wrong:

R code:

# 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()

C# code:

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

class Program
{
    static void Main(string[] args)
    {
        var rmainpath = @"C:\Program Files\R\R-4.0.3";
        var rpath = rmainpath +  @"\bin\Rscript.exe";

        var mainGoogleDrivePath = @"C:\Users\Administrator\Google Drive";
        //var scriptpath = mainGoogleDrivePath + @"\repos\rsource\Script.R";
        var scriptpath = mainGoogleDrivePath + @"\Projects\RFromCSharp\RFromCSharp\bin\Debug\Script.R";
        var output = RunRScript(rpath, scriptpath);

        Console.WriteLine(output); // output is empty
        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 })
            {
                if (false == proc.Start())
                    throw new Exception("Didn't start R");

                return proc.StandardOutput.ReadToEnd();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return string.Empty;
    }
}
Ivan
  • 7,448
  • 14
  • 69
  • 134
  • How are you calling the script from R, are you running `source()`? Your script doesn't seem to explicitly `print()` anything so when running the code non-interactively I don't think anything will print. Try changing the last line to `print(get_gbm())` if you are expecting the result to be printed to the console. – MrFlick Oct 20 '20 at 00:43
  • Not sure what you are asking re: source() - I gave the exact way I am calling the R script from C# in the code above. Adding print(gbm()) doesn't do anything. – Ivan Oct 20 '20 at 00:57
  • You said, "If I run the script from within R-GUI". It's unclear exactly what you mean by that. Did you copy/paste into the console or something. or did you run `source("Script.R")`? The latter of which is more closer to what happens when you run `Rscript`. R behaves differently when run interactively vs not. – MrFlick Oct 20 '20 at 01:02
  • In the R-GUI, I open the script, select all the txt, then hit the run button. Works perfectly. This code calls Rscript.exe, which is probably the same program except no GUI - just a console. The one thing that might be going wrong is, I installed gbm package in the GUI, but don't know if the Rscript also sees that package? – Ivan Oct 20 '20 at 01:08
  • I found almost exactly the same problem here: https://stackoverflow.com/questions/56138322/run-rscript-using-processstartinfo-from-c-sharp – Ivan Oct 20 '20 at 01:18
  • I can't replicate the problem. It runs just fine for me when I change the paths for my computer. As long are your GUI and RScript share the same `.libPaths()` it should be able to find the package. Maybe you also want to redirect standard error to see if you are getting an error message. Or try running Rscript from the command line directly to make sure it works. – MrFlick Oct 20 '20 at 01:21
  • The problem is the space in the path to the r-script. Now works! – Ivan Oct 20 '20 at 01:37

0 Answers0