I have an simple R script that takes a input value and do some calculations based on the input value and writes it in a csv file. Below is the code of my r script.
testfun=function(x){
x<-args[1]
x=sqrt(x)+(x*x)
a=x+x+x
b=data.frame(x,a)
setwd("D:\\R Script")
write.csv(b,"testfun.csv",row.names=F)
}
I am calling this rscript from my asp.net web application using Rscriptrunner provided by Jake Drew
/// <summary>
/// This class runs R code from a file using the console.
/// </summary>
public class RScriptRunner
{
/// <summary>
/// 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]);
/// </summary>
/// <param name="rCodeFilePath">File where your R code is located.</param>
/// <param name="rScriptExecutablePath">Usually only requires "rscript.exe"</param>
/// <param name="args">Multiple R args can be seperated by spaces.</param>
/// <returns>Returns a string with the R responses.</returns>
public static string RunFromCmd(string rCodeFilePath, string rScriptExecutablePath, string args, int iInput)
{
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);
}
}
}
The way that i invoke my script to rscriptrunner is as below
int x = 64;
string scriptPath = string.Format(@"C:\Program Files\R\{0}\bin\Rscript.exe", Rversion);
string path = string.Format(@"D:\testfun.r");
string result = RScriptRunner.RunFromCmd(path, scriptPath, path.Replace('\\', '/'), x);
Basically I want to provide the x value from my web application into my r Code and get the output in the csv file specified in the r script.
I tried few ways provided in the below threads
How can I read command line parameters from an R script?
Run R script with start.process in .net
However I am not able to get what i want. The script is not getting executed. I also tried by adding args<-commandArgs(TRUE) in my rscript but its not working.
Basically I am a .net developer and want to run the r script from my web application due to some client need. I am not that much aware of R and if some one helps me on how I have to pass the parameter value to my r code, it would be helpful for me.