C# not connecting to R using RDotNet

2019-06-04 15:56发布

I am trying to interface C# to R using RDotNet.

The following code is wants R to calculate the sum of two numbers and C# to get the result back and display it in the command window.

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

but when I try to send the command to R and get back the calue in x I got an error:

"InvalidOperationException was unhandled"

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

If I explore the object "engine" I see that IsRunning=false.

Can this be the problem? And how can I fix this in order to be able to interface to R?

1条回答
放荡不羁爱自由
2楼-- · 2019-06-04 16:47

It looks like you have outdated version of R.NET.

From 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.

You can update your R.NET using NuGet manager from Visual Studio. See the same documentation page for detals.

Here is code sample from the same documentatin page - note that initialization of REngine is significantly simpler now (as now Rengine looks at the Registry settings set up by the R installer):

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();
查看更多
登录 后发表回答