System Invalid Operation Exception - R.Net

Apr 3, 2014 at 2:26 PM
I am new to C# and R.Net
Running Windows7 64bit.
I am trying to call R.Net from Fidelity's WealthLab tool which allows you to create trading strategies using C#. I'd like to incorporate R's tool there.

I've written some code but do not understand why I am generating this error or what to do about it. I hope it is obvious and something simple for the people who read these discussions.

The code fails when I try to CreateInstance

Many thanks.
   public class MyStrategy :WealthScript
    {
        // instance of REngine
        private REngine _instance = null;

        // public property (getter) for your REngine instance
        
        public REngine Instance
        {
            get { return _instance; }
            set { _instance = value; }
        }

        protected override void Execute()
        {
            // Put R in the PATH
            var oldPath = System.Environment.GetEnvironmentVariable("PATH");
            var rPath = System.Environment.Is64BitProcess ? @"C:\Program Files\R\R-3.0.3\bin\x64" : @"C:\Program Files\R\R-3.0.3\bin\i386";
            var newPath = string.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath);
            System.Environment.SetEnvironmentVariable("PATH", newPath);

            // if REngine hasn't been instantiated yet (first run), create an instance
            if (this.Instance == null)
            {
                this.Instance = REngine.CreateInstance("RDotNet");
                this.Instance.Initialize(); // required since v1.5
            }

       
            
            // .NET Framework array to R vector.
            NumericVector group1 = this.Instance.CreateNumericVector(new double[] { 30.02, 35.99, 30.11, 29.97, 30.01, 29.99 });
            this.Instance.SetSymbol("group1", group1);
            // Direct parsing from R script.
            NumericVector group2 = this.Instance.Evaluate("group2 <- c(29.89, 29.93, 37.72, 29.98, 30.02, 29.98)").AsNumeric();

            // Test difference of means and get the P-value.
            GenericVector testResult = this.Instance.Evaluate("t.test(group1, group2)").AsList();

            double p = testResult["p.value"].AsNumeric().First();
            PrintDebug(p.ToString());
            
            // Run a regression analysis
            GenericVector testResult2 = this.Instance.Evaluate("lm(group1 ~ group2)").AsList();

            double c = testResult2["coefficients"].AsNumeric().First();
            NumericVector coeff = testResult2["coefficients"].AsNumeric();


        }
    }
  • BaseNamespace 'this._instance.BaseNamespace' threw an exception of type 'System.InvalidOperationException' RDotNet.REnvironment {System.InvalidOperationException}
  • base {"Operation is not valid due to the current state of the object."} System.SystemException {System.InvalidOperationException}
  • EmptyEnvironment 'this._instance.EmptyEnvironment' threw an exception of type 'System.InvalidOperationException' RDotNet.REnvironment {System.InvalidOperationException}
Developer
Apr 4, 2014 at 9:57 PM
It seems your code is correct and should work indeed. Importantly, you make sure you are creating and initializing the engine only once. (Side note: the changes to the PATH environment variable should be done once only; not that it creates an immediate problem, but a growing environment variable over time)

One possible thing to try: set the R_HOME environment variable to e.g. "c:\Program Files\R\R-3.0.3". On Windows this is normally not needed, but somehow seems to be on some machines.

Otherwise, you can give a try to use the latest development branch (you will find some pointers in a recent discussion). I also started a draft of the next documentation to get started with R.NET, at this page
Apr 4, 2014 at 10:16 PM
Thank you for that update.

This didn't work. forgive the less than technical explanation but because the Fidelity product left the program "open" in some sense and allowed you to run it on different ticker symbols it tried to initialize the engine more than once

I got rid of the public REngine Instance above and did the following, first calling GetInstanceFromID
It was quite confusing at first. Now I'm onto trying to understand differences between NumericVector and double arrays. Always fun learning new languages.
            // Put R in the PATH
            var oldPath = System.Environment.GetEnvironmentVariable("PATH");
            var rPath = System.Environment.Is64BitProcess ? @"C:\Program Files\R\R-3.0.3\bin\x64" : @"C:\Program Files\R\R-3.0.3\bin\i386";
            var newPath = string.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath);
            System.Environment.SetEnvironmentVariable("PATH", newPath);

            REngine r = REngine.GetInstanceFromID("RDotNet");

            if (r == null)
            {
                r = REngine.CreateInstance("RDotNet");
                r.Initialize();
            }