Quantcast
Channel: R.NET
Viewing all 1634 articles
Browse latest View live

Created Unassigned: GetFactors() bug [104]

$
0
0
In Factor.cs, the GetFactors() method has a bug.
This call will fail: engine.Evaluate("factor(c(\"a\", \"b\", NA, \"a\"))").AsFactor()

To fix it, the method implementation should change to:
public string[] GetFactors()
{
var levels = GetLevels();
return this.Where(value => value != int.MinValue).Select(value => levels[value - 1]).ToArray();
}

Commented Feature: Support usage of R.NET from multiple App Domains [92]

$
0
0
One problem that comes up for us quite a bit when using R.NET from the RProvider is that we need to load it into multiple appdomains simultaneously. The native R.DLL is obviously AppDomain agnostic, but the R.NET instances are completely isolated.

The concrete problem is that in the second appdomain, the R.DLL fails during initialization because it is already initialized.

Any ideas on how we could make that work? Seems like R.DLL instances would have to be managed through some native code, or we would need some process-wide flag to record the fact that R.DLL has already been initialized.

Basically this is the same issue as the multiple-initialization problem.
Comments: Thanks! In some cases I think this will help us, but in general it won't because we have some process re-use where we don't know whether previous code running in the process initialized R. But we can try to propagate that information around somehow.

New Post: Failed to use sn library on Windows 8.1 (C#, VS2010 and .NET Frame 4)

$
0
0
Hi J-M,

With your help, I'm able to use sn library in my application and it works well on Windows 7. When I try to port my application from Windows 7 to 8.1, my application failed and ParseException occurred at:
engine.Evaluate("library(sn)");
Error said "Error in the application". The setup for the R, R.NET, and sn are identical ob both OSs.

Could you please shed some light on what's wrong here?

Thanks,

Howard

New Post: Failed to use sn library on Windows 8.1 (C#, VS2010 and .NET Frame 4)

$
0
0
I cannot; I do not intuit anything obvious that could be the issue, and I do not have access to other boxes than Windows 7. If you are comfortable enough with starting from the latest source code (on the branch with my username) to compile RDotNet.dll , you probably would get a more informative error message, if the issue persist.

Source code checked in, #74518b451349

$
0
0
Fix bug where factors with NAs caused an IndexOutOfBounds https://rdotnet.codeplex.com/workitem/104.

Closed Unassigned: GetFactors() bug [104]

$
0
0
In Factor.cs, the GetFactors() method has a bug.
This call will fail: engine.Evaluate("factor(c(\"a\", \"b\", NA, \"a\"))").AsFactor()

To fix it, the method implementation should change to:
public string[] GetFactors()
{
var levels = GetLevels();
return this.Where(value => value != int.MinValue).Select(value => levels[value - 1]).ToArray();
}
Comments: Thanks for reporting this; Fixed on Revision: 272 Date: Sunday, 30 March 2014 10:14:30 AM Branch: jperraud

Commented Feature: Convenient API to create data frames from .NET [102]

$
0
0

See [this discussion](https://rdotnet.codeplex.com/discussions/539844).

Started a unit test; now that function calls with dotted pairlists works, calling the data frame function is much easier.
Feature is already implemented; needs:
- Unit tests (incl. odd cases, different vector lengths etc.)
- Assess the convenience of the API design for data frame creation.
- Support passing already existing R vectors (Actually probably already do, but may be convenient to avoid a full mem copy to better scale up to large data sets)

Comments: Well behaved cases work; however I cannot seem to get the right managed exception for incorrect arguments. I'd like not to duplicate the checks on data.frame arguments from the R native library, but it seems that I do not the same exception as errors where I can retrieve the LastErrorMessage to feed in the EvaluationException. Test Name: TestDataFrameInMemoryCreation ``` Assert.Throws(typeof(EvaluationException), (() => df = engine.CreateDataFrame(columns, columnNames: null))); ``` Result Message: System.Runtime.InteropServices.SEHException : External component has thrown an exception.

Created Unassigned: ClearGlobalEnvironment [105]

$
0
0
The ClearGlobalEnvironment is doing the following:
this.Evaluate("rm(list=ls())");

This doesn't remove hidden objects.
It should instead do:
this.Evaluate("rm(list=ls(all=TRUE))");

In addition, it might be useful to add the detach() command (to unload all packages), but this should be optional (by an argument to the function) as sometimes, between requests, it is good to leave loaded packages.

And one last thing, it might be recommended to perform the CLR garbage collection twice:
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();

This is because the finalizers execute after the first collection and you want to collect whatever they left behind.

Updated Wiki: How to contribute to the codebase

$
0
0
Cannot resolve image macro, invalid image name or id.

Updated Wiki: How to contribute to the codebase

$
0
0
Your forks - create a new fork

Log in on to codeplex; go to the R.NET source code tab. You will see a "Fork" link (right hand corner of the figure)

001.png

Create your fork. You are free to use whatever name you want for your fork(s)

002.png

The process should complete and give you a view of your newly created fork, ready to be cloned to your computer.

003.png

There are many clients for Mercurial. This documentation will show a GUI client for Mercurial and Git, http://sourcetreeapp.com/. This is not an endorsement, and I have no link to the company, it is just what I happen to use personally at the moment.

Start the cloning process of your forked repo:

004.png


005.png

Once cloned, your local checkout will be the 'default' branch. It may be what you want by the time you read this documentation.

006.png

Let's say, as is the case here, that a development branch is ahead and what you want to contribute to. It may or may not be the branch with most recent activity, the tip. for this document, lets say it is.

007.png

Doubleclick on the branch you wish to check out.

008.png

Now you should see the working copy as being the branch, 'jperraud' in this instance.

009.png

It may be optional, but I'd advise you create your own branch by clicking on the "branch" button. You should see a panel where you can name your working branch.

010.png

That's it, you have created your branch

011.png

Time to look at the code. You'll likely need to work with the solution RDotNet.Tests.sln; since you contribute, you are likely to need to test...

012.png

R.NET code uses a somewhat unusual three spaces tab indentation. You can set your C# settings to do so, but to switch back and forth between settings, you should use settings files.

013.png

014.png

While the R.NET settings we are about to load are mostly standard, you should back up your settings (or at least the C# part of it). If you have customized your settings, you really should back up anyway, to a vssettings file at a location of your choice.

015.png

Once you have backed up and are about to load the R.NET settings, click Browse:

016.png

017.png

Once the file is loaded, you have options to import only a subset of the settings. In this case, there is already a subset only: the ones dealing with C#.

018.png

If you are contributing code, in just about any case you should work in a test-driven mode. If your code contribution changes the behavior of R.NET or adds a feature. Ideally you should write a unit test before you change the functionality you are testing. Code contributions without proper unit test coverage are more likely to be (temporarily) rejected, that is until there is unit test is added.

019.png

For the sake of demonstrating how to do a pull request, let's add minor changes. The compiler says a couple of variables are unused. We remove them, and save a compile the solution. If you were doing more substantial changes, you would need to iterate until your NUnit tests pass.

020.png

Going back to the Mercurial client, it shows the modified files in orange. Refer to Mercurial and SourceTree documentation for details, but you can commit these files.

021.png

Always, always add a commit message.

022.png

It is commited to your local repository. You may do further work and commits. Let's push this commit now ("Push" button)

023.png

024.png

Once pushed, of you go back to our web browser and your fork, you can see your commit.

025.png

You can then submit a pull request, but you don't have to do this every time your commit/push work to your fork. Just submit a pull request when your overall work is ready. Note that you can specify the source and target branches; in this case we started our branch from the development 'jperraud' branch, so maybe contributions should get back there.

026.png

027.png

Done. Pending approval.

028.png

New Post: Failed to use sn library on Windows 8.1 (C#, VS2010 and .NET Frame 4)

$
0
0
Could you please advice me on how to get the latest source code on the branch with your username in detail?

New Post: Getting regression coefficients from R.Net

$
0
0
Hello

New to R.Net, somewhat less new to C# ( I mostly use VB)

Not sure how to get regression coefficients from this example. The watch window in visual studio doesn't provide much help when I look at testResult.

Thanks any help greatly appreciated.
NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 35.99, 30.11, 29.97, 30.01, 29.99 });
NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 37.72, 29.98, 30.02, 29.98)").AsNumeric();
GenericVector testResult = engine.Evaluate("lm(group1 ~ group2)").AsList();

New Post: Getting regression coefficients from R.Net

$
0
0
engine.Evaluate("coefficients(lm(group1 ~ group2))").AsNumeric();

New Post: Getting regression coefficients from R.Net

$
0
0
Thanks!

I guess I would precede it by

NumericVector coeff = engine.Evaluate("coefficients(lm(group1 ~ group2))").AsNumeric();

and then look at the elements one by one. This is a tremendous help.

New Post: Failed to use sn library on Windows 8.1 (C#, VS2010 and .NET Frame 4)

$
0
0
Going to the source tab, switching the "browsing changes in" to the branch of interest, then clicking 'Download' would give you a zip of the code on that branch.

More involved, the recently added document how to contribute to R.NET contains information on how to access a branch, with details on how to do this from a particular Mercurial client application.

New Post: An exception of type 'RDotNet.ParseException' occurred in RDotNet.dll... Additional information: Error in the application.

$
0
0
Hi,

I am trying to execute R commands from my web application. But getting the exception message "An exception of type 'RDotNet.ParseException' occurred in RDotNet.dll". code is very straight forward and simple. Just copying the example-


protected void Page_Load(object sender, EventArgs e)
    {

        // Set the folder in which R.dll locates.
        // See Documentation for automatic search of installation path.
        // This example set PATH environment variable for 64-bit process and R x64 on Windows.
        // You should appropriately set the correct location for other cases.
        // Refer to the Documentation page.
        var envPath = Environment.GetEnvironmentVariable("PATH");
        //var rBinPath = @"C:/Program Files/R/R-3.0.3/bin/i386";
        var rBinPath = @"C:\Program Files\R\R-3.0.3\bin;C:\Program Files\R\R-3.0.3\bin\i386;";
        Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);

        // For Linux or Mac OS, R_HOME environment variable may be needed.
        //Environment.SetEnvironmentVariable("R_HOME", "/usr/lib/R")
        //REngine.SetDllDirectory(@"C:\Program Files\R\R-2.15.1\bin\i386");            
        using (REngine engine = REngine.CreateInstance("RDotNet"))
        {
            // From v1.5, REngine requires explicit initialization.
            // You can set some parameters.
            engine.Initialize();

            foreach (string path in engine.Evaluate(".libPaths()").AsCharacter())
            {
                Response.Write(path);
            }


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

            // Test difference of mean and get the P-value.
            GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
            double p = testResult["p.value"].AsNumeric().First();

            //Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
            //Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
            //Console.WriteLine("P-value = {0:0.000}", p);

            Response.Write("=============OUPPUT=================");
            Response.Write("Group1: " + string.Join(", ", group1));
            Response.Write("Group2: " + string.Join(", ", group2));
            Response.Write("P-value =  " + p);
        }

    } 
But the strange thing is that when I am executing this code in side main() method in console application I am not getting any exception or error. Everything works fine.

But when executing inside Page_Load() method, I am getting exception from the line

GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();

Can you help me to find the cause of the issue and how to resolve it.

Thanks in advance.
Raj

New Post: An exception of type 'RDotNet.ParseException' occurred in RDotNet.dll... Additional information: Error in the application.

$
0
0
I assume, second guessing from the method name, that you are running from ASP.NET.
Running R from ASP.NET is problematic, and is unlikely to be an issue in R.NET itself.
If you search for ASP.NET as a keyword in the dicussion tab, you will find more background.

New Post: System Invalid Operation Exception - R.Net

$
0
0
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}

New Post: source and load direct via bytearray

$
0
0
Hello,

I have saved R scripts, workspaces and variables and stored them in a SQL database as bytearray. To transfer them back into rdotnet I load the selected information from the SQL Database in a bytearray, save this array in a file and load this file using e.g. __engine.Evaluate(@"source('file.bin');") or __engine.Evaluate(@"load('file.bin');"); again.
Is there a way to transfer them directly as bytearray to rdotnet without saving the data first into a file?

Thanx

New Post: System Invalid Operation Exception - R.Net

$
0
0
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
Viewing all 1634 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>