是否可以在C#中调用用户定义的(自定义)R函数?
例如,用R:
编写的简单矩阵乘法函数matrix_mult = function(a, b) {
c = a %*% b;
return c;
}
如何从c#?
调用此R函数matrix_mult(a,b)答案 0 :(得分:8)
1)在MS Visual Studio中打开现有项目或新项目。
2)安装R.NET(NuGet) http://rdotnet.codeplex.com
安装很简单: 菜单:Visual Studio(2012)>库包管理器>包管理器控制台 键入“Install-Package R.NET”
3)在R中初始化一个函数并从C#调用它 有关R
中的数据类型,请参阅http://rdotnet.codeplex.com/documentationusing 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();
}
}
}
答案 1 :(得分:1)