Sunday, July 15, 2012

Introduction to C# and R Integration using R-(D)COM Server

Introduction

Quantitative analysis in the financial industry space plays a major role by providing services with the use of numerical, statistical and quantitative techniques. Such services may include investment management, portfolio optimization, risk management, derivative pricing, etc. In many of the cases mentioned above statistics is a subject area that provides invaluable concepts/theories in order to aid the process of analysis. Similar to using a language when developing a software, modeling statistical concepts/theories can also be done with the help of language.

One such language that complements subject of statistics is the R Language. However R in its very own nature is a nothing more than a language to perform statistical analysis. This creates the background for integrating R with C# whereby combining the power of a .NET language and its related frameworks together with a powerful statistical language.

Purpose

In this post I aim to integrate C# with R using the R-(D)COM Server which functions as the bridge between the two languages. I have come across few articles, tutorials and quite a number of forum threads detailing the integration process between C# and R. However it was not very straight forward when I tired it out for my self, hence I thought of sharing a detailed explanation with the intention of helping you save some time if you ever are to try the same.

Prerequisites

1. R Language: The latest version of R for windows can be downloaded from The Comprehensive R Archive Network aka CRAN site.
2. R-(D)COM Server: This can be downloaded from same CRAN site by clicking on the Other link on the left and selecting the R-(D)COM Server link.
3. Visual Studio: Visual C# Express can be downloaded from here.

Solution

This solution can be performed on both Windows environments Windows 7 and 2008 R2. Ill keep it simple by listing things you need to do step-wise, and detail where ever needed.

Step 1: Install R

Start the R setup as administrator, go with the default selections and complete the R installation.

Step 2: Install rscproxy.dll

The rscproxy.dll is a required dll in order to communicate with the R-(D)COM Server and by default the native R installer will not include this. To install the .dll, open R as administrator and type in the following command.
> install.packages(“rscproxy”)
Select a mirror and click OK. This will install the rscproxy.dll as part of the R library.
Copy the rscproxy.dll from the installed location %PROGRAMFILES%/R/R-2.14.1/library/rscproxy/libs/i386 to the %PROGRAMFILES%/R/R-2.14.1/bin/i386 directory.

Step 3: Configure R_HOME and path Environment Variables

Add a new system environment variable named R_HOME to point to the root directory of the R installation. To do this open the command prompt –> type sysdm.cpl –> go to the Advanced tab –> click Environment Variables… –> click New under the System variables panel as seen below.

image

Edit the path environment variable and add location to the i386 directory in the bin directory of R as seen below.
image

Step 4: Install R-(D)COM Server

Start the R-(D)COM Interface setup as administrator, go with the default selections and complete the installation.

Step 5: Verify R and R-(D)COM Server

By default the R-(D)COM Server setup installs a set of test files to verify and test connections between the (D)COM Server and R. To perform the basic test navigate to Start –> All Programs –> R –> (D)COM Server –> Server 01 – Basic Test. When the test dialog appears click on Start R. You should see a the initialization proceed and a basic test performed as shown below.

image

Step 6: Integrating C# and R using R-(D)COM Server

This tutorial will limit the example to a very basic Console Application which evaluates a very basic R command.

1. Open Visual Studio and create a new Console Application.

2. Add the following code to the R-(D)COM Server references as shown below.
image

3. Add the following code to the Program.cs class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using STATCONNECTORSRVLib;
using System.Runtime.InteropServices;

namespace R_ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            StatConnector connector = new StatConnector();

            try
            {
                connector.Init("R");

                // Create vector x.
                connector.EvaluateNoReturn("x <- c(2,3,5,1,4,4)");

                // Basic calculations.
                Console.WriteLine(String.Format("sum(x): {0:0.00}", (double)connector.Evaluate("sum(x)")));
                Console.WriteLine(String.Format("mean(x): {0:0.00}", (double)connector.Evaluate("mean(x)")));
                Console.WriteLine(String.Format("sd(x): {0:0.00}", (double)connector.Evaluate("sd(x)")));
                Console.WriteLine(String.Format("median(x): {0:0.00}", (double)connector.Evaluate("median(x)")));
            }
            catch (COMException ex)
            {
                // Gets the text if any error occured.
                Console.WriteLine(string.Format("Unexpected COM Interop Error: {0}", connector.GetErrorText()));
            }
            finally
            {
                if (connector != null) connector.Close();
            }

            Console.ReadKey();
        }
    }
}
I will include combinations of R integrated with ASP.NET where you could leverage the power of a great web framework in order to do some really neat stuff. Please leave your feedback on any issues you encounter and I will get back to you as soon as I can.

Comments

2 comments:

  1. Hi. I think the image links for the above post might be dead. Can you fix them? Thanks!

    ReplyDelete