C#没有使用RDotNet连接到R.

时间:2014-10-03 14:06:45

标签: c# r interface com r.net

我正在尝试使用RDotNet将C#连接到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未处理”

     

“由于对象的当前状态,操作无效。”

如果我探索对象“引擎”,我会看到IsRunning=false

这可能是问题吗?我怎样才能解决这个问题,以便能够与R接口?

1 个答案:

答案 0 :(得分:3)

看起来你已经过时了R.NET版本。

来自R.NET project documentation

  

R.NET 1.5.10及其后续版本包含重大更改   特别是为了缓解用户经常处理的两个绊脚石:   R共享库的路径,并阻止多个引擎   初始化。

您可以使用Visual Studio中的NuGet管理器更新您的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();
相关问题