Karthik Venkatraman
Karthik Venkatraman

Reputation: 1657

Using RScript.exe to run a rscript with parameter

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

Passing Command

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.

Upvotes: 2

Views: 2978

Answers (3)

Karthik Venkatraman
Karthik Venkatraman

Reputation: 1657

I have found a way to provide parameter's to my function through ASP.NET C#.

Basically I created a wrapper for my r code, such that I call my real r code from another wrapper.r code in which i pass my arguments.

The wrapper code will be like below

args <- commandArgs(TRUE)
r <- as.double(args[1])
x <- as.double(args[2])
source("logistic.R")
logistic(r, x) 

Here, I am calling my real r code using the source function and passing the arguments to my logistic.R code.

Once i created the wrapper, i am executing my r code using the following code

Rscript logistic-wrapper.R 3.2 0.5

executing the logistic-wrapper.R along with the arguments 3.2 and 0.5 will execute my logistic.r code supplied with the arguments.

Upvotes: 1

Sahil Seth
Sahil Seth

Reputation: 195

You could use the package funr.

Assuming your script looks like this

# define the function
testfun <- function(x = 2, outfile = "testfun.csv"){
  x=sqrt(x)+(x*x)
  a=x+x+x
  b=data.frame(x, a)
  #setwd("D:\\R Script")
  write.csv(b,outfile,row.names=F)
}

help_text = "
This script creates a data.frame and writes it out as a CSV file.

Usage: testfunr.R testfun x=<a number> outfile=<myfile.csv>
"

library(funr)
out = funr(commandArgs(trailingOnly = TRUE), help_text = help_text)

Then simple call your function with the parameters.

Rscript testfun.r testfun x=2
# one may explicitly provide the output filename as well
Rscript testfun.r testfun x=2 outfile=myfile.csv

Upvotes: 0

cccmir
cccmir

Reputation: 1003

fastest way to do so is to run R CMD batch with args and write youre results to a file, lets say .json from command line: R CMD BATCH --slave '--args a b c'

in R:

args <- commandArgs(trailingOnly = TRUE)
a <- args[1]
b <- args[2]
c <- args[3]

and just write your results to a file

Upvotes: 0

Related Questions