2014-10-03 27 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();