Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call a user-defined (custom) R function from within C#?

Tags:

r

c#-4.0

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#?

like image 365
tuncalik Avatar asked Feb 09 '13 15:02

tuncalik


People also ask

How do you view the code of a function in R?

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.


2 Answers

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();
    }
}
}
like image 172
tuncalik Avatar answered Oct 06 '22 17:10

tuncalik


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.

like image 36
Dirk Eddelbuettel Avatar answered Oct 06 '22 17:10

Dirk Eddelbuettel