2014-10-03 60 views
1

我想使用RDotNet將C#連接到R.C#沒有使用RDotNet連接到R

以下代碼是希望R計算兩個數字和C#的總和以獲取結果並將其顯示在命令窗口中。

using System; 
using RDotNet; 

namespace rcon 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     string dllPath = @"C:\Program Files\R\R-3.1.0\bin\i386"; 

     REngine.SetDllDirectory(dllPath); 
     REngine.CreateInstance("RDotNet"); 

     //REngine engine = REngine.GetInstanceFromID("RDotNet"); 

     using (REngine engine = REngine.GetInstanceFromID("RDotNet")) 
     { 
      var x = engine.Evaluate("x <- 1 + 2"); 
      Console.WriteLine(x); 
     } 
    } 
} 
} 

但是當我嘗試將命令發送到R和取回X的calue我得到了一個錯誤:

"InvalidOperationException was unhandled"

"Operation is not valid due to the current state of the object."

如果我探索對象的「引擎」我看到IsRunning=false

這是問題嗎?我怎樣才能解決這個問題,以便能夠連接到R?

+0

'你失蹤在該字符串末尾的「\」'dllPath = @「C:\ Program Files \ R \ R-3.1.0 \ bin \ i386」 – MethodMan 2014-10-03 14:14:44

回答

3

它看起來像你有過時的R.NET版本。

R.NET project documentation

R.NET 1.5.10 and subsequent versions include significant changes notably to alleviate two stumbling blocks often dealt with by users: paths to the R shared library, and preventing multiple engine initializations.

可以使用的NuGet經理從Visual Studio更新R.NET。請參閱detals的相同文檔頁面。

下面是來自同一documentatin頁面代碼示例 - 注意的REngine即初始化顯著簡單,現在(像現在Rengine着眼於通過R安裝程序設置的註冊表設置):

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