Calling user-defined functions in R from within c#

In order to integrate R with high-level table constructs like function router1 or subtable transformer2 it might be desirable to call user-defined functions in R from within c#.

This can be done quite easily with the help of the open-source codeplex library R.NET; following steps show how.

You may also want to see the related forum topic:
How can a function router call matrix functions written in R?

1) Open an existing or new project in Microsoft Visual Studio

2) Install R.NET (NuGet)

Installation is quite easy:
Visual Studio (2012) > TOOLS > Library Package Manager > Package Manager Console
type: PM> “Install-Package R.NET”

3) Initialize a function in R and call it from C#
See R.NET documentation for data types in R and R.NET.

using RDotNet;
 
// initialize R connection
var envPath = Environment.GetEnvironmentVariable("PATH");
 
// check the version and path on your computer
var rBinPath = @"C:Program FilesRR-2.14.1binx64";
 
Environment.SetEnvironmentVariable("PATH", envPath 
	+ System.IO.Path.PathSeparator + rBinPath);
 
// initialite REngine object
using (REngine engine = REngine.CreateInstance("RDotNet"))
{
	// Initializes settings.
	engine.Initialize();
 
	// define your function in R as multi-line string
	string myfuncstr = @"matrix_mult <- function(a,b){
	c = a %*% b;
	return(c);
	}";
 
	// embed your R function here
	Function matrix_mult = engine.Evaluate(myfuncstr).AsFunction();
 
        // create input matrices
        NumericMatrix a = engine.Evaluate(@"a <- matrix(c(1,4,2,5,3,6), nrow=2)").AsNumericMatrix();
        NumericMatrix b = engine.Evaluate(@"b <- matrix(c(1,4,2,5,3,6), nrow=3)").AsNumericMatrix();
 
	// call your R function from c#
	NumericMatrix c = engine.Evaluate(@"c <- matrix_mult(a,b)").AsNumericMatrix();
 
	// ...
}
3 or subtable transformer ((A subtable transformer applies the same table (or matrix) function on every subtable of" data-image="" data-button=""> Share
  1. A function router applies selected table (or matrix) functions on selected subtables of an input table. []
  2. A subtable transformer applies the same table (or matrix) function on every subtable of an input table. []
  3. A function router applies selected table (or matrix) functions on selected subtables of an input table. []
This entry was posted in Calculation engine and tagged , . Bookmark the permalink.

Leave a Reply