R.Net 用法


using (REngine engine = REngine.CreateInstance("RDotNet")) { engine.Initialize(); var expandGrid = 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 = expandGrid.Invoke(new SymbolicExpression[] {v1, v2}).AsDataFrame(); engine.SetSymbol("cases", df); // Not correct: the 'y' column is a "factor". This returns "1", "1", "1", "2", "2", etc. var letterCases = engine.Evaluate("cases[,'y']").AsCharacter().ToArray(); // This returns something more intuitive for C# Returns 'a','a','a','b','b','b','c' etc. letterCases = engine.Evaluate("as.character(cases[,'y'])").AsCharacter().ToArray(); // In the manner of R.NET, try letterCases = engine.Evaluate("cases[,'y']").AsFactor().GetFactors();

          TestDataFrame(engine); Console.WriteLine("Press any key to exit the program"); Console.ReadKey(); } private static void TestDataFrame(REngine engine) { // import csv file engine.Evaluate("dataset<-read.table(file.choose(), header=TRUE, sep = ',')"); // retrieve the data frame DataFrame dataset = engine.Evaluate("dataset").AsDataFrame(); for (int i = 0; i < dataset.ColumnCount; ++i) { Console.WriteLine("Column: {0} {1}", i, dataset.ColumnNames[i]); } for (int i = 0; i < dataset.RowCount; ++i) { Console.WriteLine("Row: {0} {1}", i, dataset.RowNames[i]); for (int k = 0; k < dataset.ColumnCount; ++k) { Console.WriteLine("Cell[{0},{1}]={2}", i, k, dataset[i, k]); } } }

 

posted on 2014-01-25 17:50  大Z  阅读(680)  评论(0编辑  收藏  举报