是否可以从C#中调用用户定义的(自定义)R函数? [英] Is it possible to call a user-defined (custom) R function from within C#?
问题描述
可以从C#中调用用户定义的(自定义)R函数。
Is it possible to call a user-defined (custom) R function from within C#?
例如,一个简单的矩阵乘法函数R:
For example a simple matrix multiplication function written in R:
matrix_mult = function(a, b) {
c = a %*% b;
return c;
}
如何从c#调用此R函数matrix_mult(a,b)?
How can I call this R function matrix_mult(a,b) from c#?
推荐答案
经过一番研究,我自己找到了答案。
After some research I've found an answer myself.
1)在MS Visual Studio中打开现有的或新的项目。
1) Open an existing or new project in MS Visual Studio.
2)安装R.NET(NuGet)
http://rdotnet.codeplex.com
2) Install R.NET (NuGet) http://rdotnet.codeplex.com
安装很简单:
菜单:Visual Studio(2012 )>库包管理器>包管理器控制台
类型安装包R.NET
Installation is easy: Menu: Visual Studio (2012) > Library Package Manager > Package Manager Console type "Install-Package R.NET"
3)在R中初始化一个函数并从C#
请参见 http://rdotnet.codeplex.com/documentation 了解R中的数据类型
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();
}
}
}
这篇关于是否可以从C#中调用用户定义的(自定义)R函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!