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\"
Here is the class I recently wrote for this purpose. You can also pass in and return arguments from C# and R:
///
/// This class runs R code from a file using the console.
///
public class RScriptRunner
{
///
/// 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]);
///
/// File where your R code is located.
/// Usually only requires "rscript.exe"
/// Multiple R args can be seperated by spaces.
/// Returns a string with the R responses.
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);
}
}
}