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

c#-4.0, r

Solution

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();
    }
}
}

Problem

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

Original source