您的位置:首页 > 编程语言 > C#

c#调用R

2016-03-04 11:36 381 查看

R.NET使用文档

介绍

本页面涉及R.NET1.5.13。 1.5.13版本在功能上等同于1.5.12,但可作为一个包在NuGet.org上获得。

R.NET使.NET框架与R统计语言在同一进程进行互操作。 R.NET需要.NET Framework 4的并有R环境中安装的本地的DLL。您可以使用R.NET用在.NET的任何语言(它已被用于至少C#,F#,Vb.NET,IronPython中)。你使用这个文档之前有几个相关的事项都必须被提及。对于F#,你应该考虑F# - [R提供商。一个动机释放1.5.13对于RProvider更轻松地管理R.NET依赖。

入门

这个网页主要介绍R.NET是众所周知的跨平台运行。
作为1.5.10版本,R.NET二进制文件是平台无关的。您可能需要设置一些Linux发行版的小附加的解决方法(CentOS的是已知的),但你可以使用的。R.NET二进制文件来移动和跨平台。

Visual Studio中

如果您正在使用从zip文件分发二进制文件,解压缩文件和内容复制到您选择的位置。添加项目引用到RDotNet.dll和RDotNet.Native.dll“通常”的方式。

NuGet是首选的方式来管理R.NET依赖性。

如果您正在使用的NuGet包:

首先,您必须安装,如果你有没有准备好,通过工具的的NuGet包管理器 - 扩展和更新:

Visual Studio中

如果您正在使用从zip文件分发二进制文件,解压缩文件和内容复制到您选择的位置。添加项目引用到RDotNet.dll和RDotNet.Native.dll“通常”的方式。

的NuGet是首选的方式来管理R.NET依赖性。

如果您正在使用的NuGet包:

首先,您必须安装,如果你有没有准备好,通过工具的的NuGet包管理器 - 扩展和更新:

您可以添加R.NET包作为一个依赖于一个或多个项目在您的解决方案。对于一个项目:

请注意,你或许应该卸载软件包的依赖或R.NET1.5.5或更早的版本,如果预先存在的。

R.NET1.5.13使用不同的包装标识:R.NET.Community。请务必使用搜索R.NET上的NuGet最近条目:

该系统的NuGet然后增加了一些依赖。

您可以一气呵成的解决方案级别管理的几个项目:

你可以找到有关的NuGet在文档的NuGet更一般的信息
http://docs.nuget.org/

入门编码

R.NET1.5.10及以后的版本包括显著明显的变化,以缓解2块绊脚石,处理方式往往是由用户处理:路径与R共享库,并防止发动机多初始化。

下面的“Hello World”示例说明了如何使用新的API为90%的在Windows窗体上使用的情况下更简单:

static void Main(string[] args)
{
REngine.SetEnvironmentVariables(); // <-- May be omitted; the next line would call it.
REngine engine = REngine.GetInstance();
// A somewhat contrived but customary Hello World:
CharacterVector charVec = engine.CreateCharacterVector(new[] { "Hello, R world!, .NET speaking" });
engine.SetSymbol("greetings", charVec);
engine.Evaluate("str(greetings)"); // print out in the console
string[] a = engine.Evaluate("‘Hi there .NET, from the R engine‘").AsCharacter().ToArray();
Console.WriteLine("R answered: ‘{0}‘", a[0]);
Console.WriteLine("Press any key to exit the program");
Console.ReadKey();
engine.Dispose();
}

您检索单个REngine对象实例,设置必要的环境变量之后。甚至调用SetEnvironmentVariables可以省略,但我们会建议你把它明确。 SetEnvironmentVariables,在Windows上,着眼于建立是R安装程序的注册表设置。如果需要,您可以覆盖行为设置环境变量和发动机初始化用自己的方式,在附录中详细说明。

示例代码

你通常与REngine对象交互的方法是Evaluate,GetSymbol和SetSymbol。创建R向量和矩阵,所述REngine对象具有扩展方法如CreateNumericVector,CreateCharacterMatrix等。最后,可以以各种方式调用R里面的函数,使用Evaluate方法执行REngine对象,并且还更直接。
基本的例子采用t-test统计

它是可从示例代码在:https://github.com/jmp75/rdotnet-onboarding获取。

static void Main(string[] args)
{
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance();
// REngine requires explicit initialization.
// You can set some parameters.
engine.Initialize();

// .NET Framework array to R vector.
NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });
engine.SetSymbol("group1", group1);
// Direct parsing from R script.
NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();

// Test difference of mean and get the P-value.
GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
double p = testResult["p.value"].AsNumeric().First();

Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
Console.WriteLine("P-value = {0:0.000}", p);

// you should always dispose of the REngine properly.
// After disposing of the engine, you cannot reinitialize nor reuse it
engine.Dispose();
}

数字向量

下面的代码示例说明了最常用的功能。它是从样本代码2萃取在https://github.com/jmp75/rdotnet-onboarding,这个例子说明了数值向量的基本操作。

var e = engine.Evaluate("x <- 3");// You can now access x defined in the R environment
NumericVector x = engine.GetSymbol("x").AsNumeric();
engine.Evaluate("y <- 1:10");
NumericVector y = engine.GetSymbol("y").AsNumeric();

调用R里面的函数

虽然你可以通过生成字符串并用Evaluate函数调用,并调用Evaluate方法,这可能是笨拙的,因为你传递大量数据。下面演示了如何可以调用一个函数,有点像你会如何映射在.NET中并调用一个函数。

// Invoking functions; Previously you may have needed custom function definitions
var myFunc = engine.Evaluate("function(x, y) { expand.grid(x=x, y=y) }").AsFunction();
var v1 = engine.CreateIntegerVector(new[] { 1, 2, 3 });
var v2 = engine.CreateCharacterVector(new[] { "a", "b", "c" });
var df = myFunc.Invoke(new SymbolicExpression[] { v1, v2 }).AsDataFrame();

R.NET1.5.10包含了许多改进,以支持直接调用函数从C#,用更少的字符串操作,少REngine.Evaluate沟通。

// As of R.NET 1.5.10, more function call syntaxes are supported.
var expandGrid = engine.Evaluate("expand.grid").AsFunction();
var d = new Dictionary<string, SymbolicExpression>();
d["x"] = v1;
d["y"] = v2;
df = expandGrid.Invoke(d).AsDataFrame();

我们使用expand.grid的结果继续进行,将下面的代码说明,虽然R.NET试图模仿R的行为来对应数据集。数据集为R的数据结构的核心部分,所以值得扩展,下面几个例子:

engine.SetSymbol("cases", df);
// As of R.NET 1.5.10, factor to character expressions work consistently with R
var letterCases = engine.Evaluate("cases[,‘y‘]").AsCharacter().ToArray();
// "a","a","a","b","b","b", etc. Same as as.character(cases[,‘y‘]) in R
// Note that this used to return  "1", "1", "1", "2", "2", etc. with R.NET 1.5.5

还有其他的方法来提取数据集的列,而不通过R表达式字符串:

// Equivalent:
letterCases = df[1].AsCharacter().ToArray();
letterCases = df["y"].AsCharacter().ToArray();

2维索引返回的行为通常直接反映了R.。唯一的例外是行名失踪,R的行为是值得商榷的,所以R.NET喜欢严格。

// Accessing items by two dimensional indexing
string s = (string)df[1, 1]; // "a"
s = (string)df[3, 1]; // "a"
s = (string)df[3, "y"]; // "b"
// s = (string)df["4", "y"]; // fails because there are no row names
df[3, "y"] = "a";
s = (string)df[3, "y"]; // "a"
df[3, "y"] = "d";
s = (string)df[3, "y"]; // null, because we have an <NA> string in R

调用R脚本

要重用整个脚本,最简单的方法是使用R中的“sourece”方法

engine.Evaluate("source(‘c:/src/path/to/myscript.r‘)");

遗漏值

占位符,展示了不同各种向量类型NA值的相互交互转换情况,在后面的页面中能找到数据类型部分的详细介绍。

进一步的例子

纵观根据项目RDotNet.Tests单元测试将提供R.NET用途和编程成语的进一步信息。展示出的数据传输的速度。

运行时性能

占位符,显示出最佳做法,以最大限度地提高运行速度

其他例子还记录

占位符
处理的日期和时间

数据类型

R中的所有表达式都表示为Symbolic Expression对象在R.NET对象中。对于数据访问,下面有特殊类定义。请注意,“NA”在R特殊值值用于某些类型在这里没有直接等同于.NET中的对象,但要注意这种行为,以免风险计算不正确。

表如下。如下R.NET类构成了R和.NET框架之间的桥梁。

RR.NET.NET FrameworkNote
character vectorRDotNet.CharacterVectorSystem.String[]
integer vectorRDotNet.IntegerVectorSystem.Int32[]The minimum value in R is -2^31+1 while that of .NET Framework is -2^31. Missing values are int.MinValue
real vectorRDotNet.NumericVectorSystem.Double[]Missing values are represented as double.NaN
complex vectorRDotNet.ComplexVectorSystem.Numerics.Complex[]System.Numerics assembly is required for .NET Framework 4.
raw vectorRDotNet.RawVectorSystem.Byte[]
logical vectorRDotNet.LogicalVectorSystem.Boolean[]
character matrixRDotNet.CharacterMatrixSystem.String[, ]
integer matrixRDotNet.IntegerMatrixSystem.Int32[, ]The minimum value in R is -2^31+1 while that of .NET Framework is -2^31.
real matrixRDotNet.NumericMatrixSystem.Double[, ]
complex matrixRDotNet.ComplexMatrixSystem.Numerics.Complex[, ]Reference to System.Numerics assembly is required.
raw matrixRDotNet.RawMatrixSystem.Byte[, ]
logical matrixRDotNet.LogicalMatrixSystem.Boolean[, ]
listRDotNet.GenericVectorFrom version 1.1.
data frameRDotNet.GenericVectorFrom version 1.1. RDotNet.DataFrame class is also available (below).
data frameRDotNet.DataFrameFrom version 1.3. And from version 1.5.3,DataFrameRowAttribute and DataFrameColumnAttribute are available for data mapping.
functionRDotNet.FunctionFrom version 1.4. Including closure, built-in function, and special function.
factorRDotNet.FactorSystem.Int32[]From version 1.5.2.
S4RDotNet.S4ObjectNot Available Yet. See S4 branch in the source control.

demo1

http://rdotnet.codeplex.com/wikipage?title=Examples&referringTitle=Home

demo2

http://dynamicdatadisplay.codeplex.com/

c#调用R语言(原创翻译)

标签:class log com 代码 使用 http src si java

原文:http://blog.csdn.net/guoer9973/article/details/45953471
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: