是否可以从 C# 中调用用户定义的(自定义)R 函数?
例如用 R 编写的简单矩阵乘法函数:
matrix_mult = function(a, b) {
c = a %*% b;
return c;
}
如何从 c# 调用这个 R 函数 matrix_mult(a,b)?
经过一番研究,我自己找到了答案。
1) 在 MS Visual Studio 中打开现有或新项目。
2) 安装 R.NET (NuGet) http://rdotnet.codeplex.com
安装很简单:菜单:Visual Studio (2012) > Library Package Manager > Package Manager Console type "Install-Package R.NET"
3) 在 R 中初始化一个函数并从 C# 调用它 有关R 中的数据类型,请参见http://rdotnet.codeplex.com/documentation
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();
}
}
}