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;
}
}