C # Call R language (original translation)

Source: Internet
Author: User

R.net Introduction to the use of documents

This page covers r.net1.5.13. The 1.5.13 version is functionally equivalent to 1.5.12, but can be obtained as a package on nuget.org.

R.net enables the. NET Framework to interoperate with the R statistical language in the same process. R.net requires the. NET Framework 4 and has a local DLL installed in the R environment. You can use r.net in any language that is used in. NET (it has been used in at least c#,f#,vb.net,ironpython). Before you use this document, there are several related issues that must be mentioned. For F #, you should consider F #-[R Provider]. A motive to release 1.5.13 is easier for Rprovider to manage r.net dependencies.

Entry

This page mainly introduces r.net is well known for cross-platform operation.
As of version 1.5.10, r.net binaries are platform-independent. You may need to set some Linux distributions for small additional workarounds (CentOS is known), but you can use the. r.net binary files to move and cross-platform.

In Visual Studio

If you are using a binary file that is distributed from a zip file, unzip the files and copy the content to the location of your choice. Add project references to RDotNet.dll and RDotNet.Native.dll "usual" way.

NuGet is the preferred way to manage r.net dependencies. If you are using a NuGet package:

First of all, you must install, if you have not prepared, the NuGet Package Manager through the tools-extensions and updates:

In Visual Studio

If you are using a binary file that is distributed from a zip file, unzip the files and copy the content to the location of your choice. Add project references to RDotNet.dll and RDotNet.Native.dll "usual" way.

NuGet is the preferred way to manage r.net dependencies.

If you are using a NuGet package:

First of all, you must install, if you have not prepared, the NuGet Package Manager through the tools-extensions and updates:

You can add the R.net package as a dependency on one or more projects in your solution. For a project:

Please note that you should probably uninstall dependencies or r.net1.5.5 or earlier versions of packages if pre-existing.

R.net1.5.13 uses a different packing mark: r.net.community. Be sure to use the latest NuGet entry on the search r.net:

The system of NuGet then adds a few dependencies.

You can manage several projects at the one Go solution level:

You can find more general information about NuGet in the document NuGet
http://docs.nuget.org/

Getting Started code

The r.net1.5.10 and later versions include significant changes to alleviate the 2 stumbling blocks that are often handled by the User: Paths and R shared libraries, and prevents multiple initialization of the engine.

The following "Hello World" example demonstrates how to use the new API for 90% in cases where it is easier to use on Windows Forms:

static void Main (string[] args) {Rengine. Setenvironmentvariables();//<--may 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 consoleString[] 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();}

You retrieve a single Rengine object instance after you set the necessary environment variables. Even calling Setenvironmentvariables can be omitted, but we will advise you to make it explicit. Setenvironmentvariables, on Windows, looks at establishing registry settings that are R installers. If required, you can override the behavior setting environment variables and engine initialization in your own way, detailed in the appendix.

Sample code

The methods you typically interact with Rengine objects are Evaluate,getsymbol and Setsymbol. Create r vectors and matrices, the Rengine object has extension methods such as Createnumericvector,createcharactermatrix, and so on. Finally, functions inside R can be called in various ways, using the Evaluate method to execute the Rengine object, and more directly.
The basic example uses T-test statistics

It is available from the sample code in: Https://github.com/jmp75/rdotnet-onboarding.

static void Main (string[] args) {Rengine. Setenvironmentvariables();Rengine engine = Rengine. GetInstance();Rengine requires explicit initialization. You canSetSome parameters. Engine. Initialize();//. NETFramework 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 andGet 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();}
Digital vector

The following code example illustrates the most common features. It is extracted from sample code 2 in Https://github.com/jmp75/rdotnet-onboarding, this example illustrates the basic operation of a numerical vector.

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

Although you can call with the evaluate function by generating a string and calling the Evaluate method, this can be awkward because you are passing a lot of data. The following shows how a function can be called, somewhat like how you would map it in. NET and call a function.

//invoking functions; Previously you 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 contains a number of improvements to support direct call functions from C #, with fewer string operations and less rengine.evaluate communication.

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

We continue with the results of Expand.grid, as shown in the following code, although r.net attempts to mimic the behavior of R to correspond to the dataset. Datasets are a core part of the data structure of R, so it is worth extending, following a few examples:

Engine. Setsymbol ("Cases", DF);//AS ofR.net1.5. Ten, Factor to characterExpressions work consistently withRvar lettercases = engine. Evaluate ("cases[, ' y ']"). Ascharacter (). ToArray ();//"a","a","a","B","B","B", etc. Same as As.character(cases[,' y‘])inchr//Note that this used to return  "1","1","1","2","2", etc. withR.net1.5. 5

There are other ways to extract the columns of a dataset without using an R expression string:

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

The behavior returned by the 2-D index usually directly reflects the R: The only exception is that the row name is missing and R's behavior is debatable, so r.net likes to be strict.

Accessing items by dimensional indexingstrings = (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 is no row namesdf[3,"Y"] ="a"; s = (string) df[3,"Y"]; //"a"df[3,"Y"] ="D"; s = (string) df[3,"Y"]; //NULL, because we have a <NA>string inchR
Invoke R script

The simplest way to reuse an entire script is to use the "Sourece" method in R

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

placeholder, showing the different kinds of vector-type na value of the mutual conversion of the situation, in the following pages can be found in the data type section of the detailed description.

A further example

Throughout the project Rdotnet.tests unit tests will provide further information on r.net uses and programming idioms. Shows the speed of the data transfer.

Run-time performance

placeholder, showing best practices to maximize running speed

Other examples also record

Placeholder
Date and time of processing

Data type

All expressions in R are represented as symbolic expression objects in the R.net object. For data access, there are special class definitions below. Note that the "NA" value in R special values is used for some types where there is no direct equivalent to objects in. NET, but be aware of this behavior to avoid risk calculations being incorrect.

The table below. The following r.net classes form the bridge between R and. NET Framework.

R r.net . NET Framework Note
Character Vector Rdotnet.charactervector System.string[]
Vector integer Rdotnet.integervector System.int32[] The minimum value in R is-2^31+1 while the. NET Framework is-2^31. Missing values is int. MinValue
Real Vector Rdotnet.numericvector System.double[] Missing values are represented as double. NaN
Complex vector Rdotnet.complexvector System.numerics.complex[] System.numerics assembly is required for. NET Framework 4.
Raw vector Rdotnet.rawvector System.byte[]
Logical vector Rdotnet.logicalvector System.boolean[]
Character Matrix Rdotnet.charactermatrix system.string[,]
Integer matrix Rdotnet.integermatrix system.int32[,] The minimum value in R is-2^31+1 while the. NET Framework is-2^31.
Real Matrix Rdotnet.numericmatrix system.double[,]
Complex matrix Rdotnet.complexmatrix system.numerics.complex[,] Reference to System.numerics assembly is required.
Raw matrix Rdotnet.rawmatrix system.byte[,]
Logical matrix Rdotnet.logicalmatrix system.boolean[,]
List Rdotnet.genericvector From version 1.1.
Data frame Rdotnet.genericvector From version 1.1. Rdotnet.dataframe class is also available (below).
Data frame Rdotnet.dataframe From version 1.3. And from version 1.5.3, Dataframerowattribute and Dataframecolumnattribute is available for data mapping.
function Rdotnet.function From version 1.4. Including closure, built-in function, and special function.
Factor Rdotnet.factor System.int32[] From version 1.5.2.
S4 Rdotnet.s4object Not 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 # Call R language (original translation)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.