Is it possible to call a user-defined (custom) R function from within C#?
For example a simple matrix multiplication function written in R:
matrix_mult = function(a, b) {
c = a %*% b;
return c;
}
How can I call this R function matrix_mult(a,b) from c#?
If you want to view the code built-in to the R interpreter, you will need to download/unpack the R sources; or you can view the sources online via the R Subversion repository or Winston Chang's github mirror.
After some research I've found an answer myself.
1) Open an existing or new project in MS Visual Studio.
2) Install R.NET (NuGet) http://rdotnet.codeplex.com
Installation is easy: Menu: Visual Studio (2012) > Library Package Manager > Package Manager Console type "Install-Package R.NET"
3) Initialize a function in R and call it from C# See http://rdotnet.codeplex.com/documentation for data types in R
using RDotNet;
class Program
{
static void Main(string[] args)
{
// Set the folder in which R.dll locates.
var envPath = Environment.GetEnvironmentVariable("PATH");
// check the version and path on your computer
var rBinPath = @"C:\Program Files\R\R-2.14.1\bin\x64";
Environment.SetEnvironmentVariable("PATH", envPath + System.IO.Path.PathSeparator + rBinPath);
using (REngine engine = REngine.CreateInstance("RDotNet"))
{
// Initializes settings.
engine.Initialize();
// create an R function
// R style
// See: http://rdotnet.codeplex.com/wikipage?title=Examples&referringTitle=Home
Function matrix_mult = engine.Evaluate(@"matrix_mult <- function(a,b){
c = a %*% b;
return(c);
}").AsFunction();
NumericMatrix d = engine.Evaluate(@"d <- matrix_mult(a,b)").AsNumericMatrix();
Console.WriteLine("Matrix d:");
engine.Evaluate("print(d)");
// convert NumericMatrix of R to double[,] of .net
double[,] darr = new double[d.RowCount, d.ColumnCount];
d.CopyTo(darr, d.RowCount, d.ColumnCount);
Console.ReadKey();
}
}
}
Short answer: No.
Slightly longer answer: Wrong tool chain. R on Windows is built with the MinGW gcc port. Linking is somewhere between impossible to very fragile.
You can only do this with weak coupling using two machines, having Rserve on one and a .Net / C# connection to it. There are a few solution out there as eg RserveCLI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With