Jan 29, 2017

Executing R Script Files from C# with R.NET





1. Introduction

The photo is Suimono :) It includes Ebi Shinjyo, which is a steamed shrimp dumpling.

In this article, I note how to execute R script files from C# and the execution results. I integrated C# and R with R.NET. R.NET has so simple APIs and is easy to use.

・R.NET
 https://github.com/jmp75/rdotnet

The versions of .NET Framework, R.NET and R are as follows.

.NET Framework 4.5
R.NET 1.6.5
R 3.3.2

2. Integrating C# and R

I want to use R to execute machine learning models, display useful charts and so on, and C# to process various parameters and pass them to R. It's because R has the good capabilities of graphical processing and machine learning but isn't good at handling objects.
And I also want to incorporate R script files implemented by other persons such as quantitative analysts and data scientists, into C# applications.

2.1. C# Program

First, I note the C# program. It's required to pass arguments from it to a R script file and run the R script file. These are realized by the following methods. It's so simple :)

・ passing arguments from C# programs to R script files
REngine.SetCommandLineArguments (string[] parameters)
・ running R script files
REngine.Evaluate ("source('script file path')")


The full source code is as follows :)

・ Program.cs
using RDotNet;

namespace FinancialEngineering
{
    class Program
    {
        static void Main(string[] args)
        {
            var scriptFilePath = "C:/dev/R/test_script.R";
            var riskCsvPath = "C:/dev/R/test_data.csv";
            var valueAtRisk = "25750000000";

            ExecuteScriptFile(scriptFilePath, riskCsvPath, valueAtRisk);
        }


        public static void ExecuteScriptFile(string scriptFilePath, string paramForScript1,
                                                                                                     string paramForScript2)
        {
            using (var en = REngine.GetInstance())
            {
                var args_r = new string[2] { paramForScript1, paramForScript2 };
                var execution = "source('" + scriptFilePath + "')";

                en.SetCommandLineArguments(args_r);
                en.Evaluate(execution);

            }
        }
    }
}



'C:/dev/R/test_data.csv' in this program is like the following csv file.

・ test_data.csv
date,risk_value
20160128,21261339422
20160129,22759109989
20160130,21405741891
...


2.2. R Script File

Next, I wrote the following R script file. It's important that the arguments passed from the C# program become available  by 'args <- commandArgs()'. These are stored after 'args[2]'.

・ test_script.R
args <- commandArgs()
riskValueFilepath <- args[2]
VaR <- args[3]


data <- read.csv(riskValueFilepath, header = TRUE)
attach(data)
x <- strptime(data$date, '%Y%m%d', tz = '')

par(xaxt = 'n')

plot(x, data$risk_value, type = 'n', xlab = '',ylab ='')
lines(x, data$risk_value, type = 'l',col = 'thistle4',add = T)
points(x, data$risk_value, type = 'p',pch = 20,col = ifelse(data$risk_value > VaR, 'tomato', 'thistle4'), add = T)

par(xaxt = 's')

y <- as.POSIXct(round(range(x), "days"))
axis.POSIXct(1,at = seq(y[1],y[2],by = "1 day"),format = '%Y%m%d')
title('Test of Integrating C# and R\n(Points above Value at Risk)', xlab = 'Date',ylab = 'Risk Value')


3. Execution Result

The execution result is as follows. It noramlly ran :)



4. Conclusion

R.NET enables you to intagrate C# and R. Because passing arguments from C# to R and running R script files are possible, it's easy to incorporate  R script files into C# applications.

11 comments:

  1. Hello InuT,

    This is a very nice introduction articles. I duplicated the C# and R codes, the code seems work well. But I always run into an unhandled exception. The error messages like before while I run en.Evaluate(execution) in C#:

    "An unhandled exception of type 'RDotNet.EvaluationException' occurred in RDotNet.dll

    Additional information: Error in eval(expr, envir, enclos) : object 'p' not found"

    I am wondering if you have a way to avoid this error.

    Thanks.

    Oliver

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. I also try it, but as soon as I include sources or libraries I get the same error, Oliver any work around?

      David

      Delete
  2. Hello InuT,

    How can I make it work for user library ( additionally installed R packages)?
    Does it work for outside base R?

    ReplyDelete
    Replies
    1. How can I make it work for user library ( additionally installed R packages)?
      Yes the ones I tried are installed in R after installation, and also some of them where made by my as a Library with functions.
      Does it work for outside base R? Whe I run the equivalent script direct in R it works Fine.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Thank you for your guide to with upgrade information
    .NET Online Course

    ReplyDelete
  5. Thank you for your guide to with upgrade information
    .NET Online Course

    ReplyDelete