Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R script form C#. Passing arguments, running script, retrieving results

Tags:

c#

r

I'd like to know if its possible to run an Rscript while passing in a list of values, have that R script run and then output a resluting list of values back to c#.

I've seen people say that R.NET is good but I've only seen examples of using it to create values directly, manipulate them, access them etc when what I want to do is run already created scripts that will take in data, process it and return data. I also know that I could do this with csv files but the point is I would like to cut out the middle man.

like image 437
EvilWeebl Avatar asked Dec 24 '12 11:12

EvilWeebl


People also ask

What does the c () mean in R?

The c function in R programming stands for 'combine. ' This function is used to get the output by giving parameters inside the function. The parameters are of the format c(row, column). With the c function, you can extract data in three ways: To extract rows, use c(row, )

How do you call c from R?

Calling C functions from R Call is to use . External . It is used almost identically, except that the C function will receive a single argument containing a LISTSXP , a pairlist from which the arguments can be extracted. This makes it possible to write functions that take a variable number of arguments.

Why do we use c in R?

c() function in R Language is used to combine the arguments passed to it.

How do I write a script in R?

To start writing a new R script in RStudio, click File – New File – R Script. Shortcut! To create a new script in R, you can also use the command–shift–N shortcut on Mac.


Video Answer


1 Answers

This question is about 5 years old and there are some answers available for this like here. I will go through it with a very simple R script.

It is good to start with this link

In this simple example, I pass 3 to R, add it with 5 and get the result (8) back.

Steps

  1. Create a text file as name.r, with your r code, something like below. I named it as rcodeTest.r

    library(RODBC) # you can write the results to a database by using this library
    args = commandArgs(trailingOnly = TRUE) # allows R to get parameters
    cat(as.numeric(args[1])+5)# converts 3 to a number (numeric)
    

Then create a c# class (call it anything, I called it RScriptRunner) like below, also available at here. This is a simple class which just calls a procedure (an exe file)

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Web;

    /// <summary>
    /// Summary description for RScriptRunner
    /// </summary>
    public class RScriptRunner
    {
        public RScriptRunner()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        // 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]);
        ///  
        ///   
        /// rCodeFilePath          - File where your R code is located.
        /// rScriptExecutablePath  - Usually only requires "rscript.exe"
        /// args                   - 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();

                }

                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("R Script failed: " + result, ex);
            }
        }
    }

Then call and pass parameters like

     result = RScriptRunner.RunFromCmd(path + @"\rcodeTest.r", @"D:\Programms\R-3.3.3\bin\rscript.exe", "3");

rscript.exe is located in your R directory, and path is the location of your r script (rcodeTest.r)

Now you can have the result 8=5+3 as output as shown below. enter image description here

like image 143
Mohsen Sichani Avatar answered Oct 16 '22 07:10

Mohsen Sichani