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!
Thanks for sharing. Helped me a lot.
ReplyDeleteYou're welcome!
DeleteHello,thanks for article, it is really helpful.
ReplyDeleteHowever I do not get any output in the console. Do you have any idea ?
You are welcome!
Delete1. 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.
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)
Deletei.e
var info = new ProcessStartInfo
{
FileName = rpath,
WorkingDirectory = Path.GetDirectoryName(scriptpath),
Arguments = Path.GetFileName(scriptpath),
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false
};
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
ReplyDeleteHello,
ReplyDeleteI'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.
You probably don't have gbm library
DeleteHi!
ReplyDeleteIs there a way to get the ooutput from R Console as it is being written?
thanks!
Hi,
ReplyDeleteI tried this function with R script that write files.
The files are not created and no errors appear.
Any recommendations?
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:
ReplyDeletevar scriptpath = @"D:\repos\rsource\Script.R";
Should have been written as:
var scriptpath = @"D:\repos\rsource\gbm_test.R";
you are right, corrected it!
DeleteFrom visual studio it is working fine, however it is not working when i host in IIS, i am using .net core api
ReplyDelete