By   March 23, 2014

R has become an industry standard for statistical computations. It is natural to wonder how we can use it from our .net applications. Definitely, this quest have landed you here. Let’s begin…

Setting Up R On your Machine

In order to run R script, we would need R runtime to be installed on the machine running the process. We can download it from CRAN. You can use the following link:


You can find the installation folder under Program Files directory. The exact directory would definitely depend upon the version of R being installed. Here we have installed version 3.0.3 of the library.


Since this would require the installed R libraries on your machine, it needs to know the installation directory of R. In order to keep your life simple, you can just add bin\{platform} path to PATH environment variable.


Installing R.Net

There are a number of options for C# projects to interact with R. Here we are introducing one such option. This is R.Net. This is open source project available on CodePlex with New BSD license. For easier integration with .net code, it is also available as a nuget package. Here we are installing the nuget package with Nuget Package Manager Console tool.


Just a semantic issue, the parameter to Evaluate engine is called statement. Generally, a statement is not expected to return a value. Since this would result in a value, let’s keep calling it as expression in our language.

Evaluating Scalar Expressions using R Engine

Let’s first have a look at how we can use R for scalar expression evaluation. Since this should involve no parameters, we can also use memoization to improve performance. Here the method is using REngine from R.Net. The engine is using R’s eval feature for expression evaluation. It needs to specify that the expression is needed to be parsed from text before handing it over to eval. Here we are assuming the result as numeric.

Now we can use this method from Main method of our Console application. This is just passing the expression as string. After receiving the result back, it just prints it to the console.

Passing Variables and Expressions

Now what happens if the script requires a parameter. Let’s assume an expression with a paramter [“5 + NUM * 2 – 2”]. Here the script has NUM as a parameter. In the following, we are passing the list of parameters in a Dictionary<string, SymbolicExpression>. We are using the parameters to set symbols in the engine. We are using the expression similarly as the previous example.

Since we know the required list of parameters for the script, we can create a Dictionary of symbols. This is the same collection used by the above code to set parameter symbols.

Download Code

Category: R Tags: