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

New Post: How to return result from Rscript after execute code in R.NET

$
0
0
A code sample to get started from is:
var npkscript = @"
op <- options(contrasts = c('contr.helmert', 'contr.poly'))
npk.aov <- aov(yield ~ block + N*P*K, npk)
npk.sum <- summary(npk.aov)
            ";
            engine.Evaluate(npkscript);
            var m = engine.GetSymbol("npk.sum").AsList();
            var df = m [0].AsDataFrame();
            var names = df.Names;
            var colnames = df.ColumnNames;
            // should do some checkes on namesdouble[] meanSqr = df["Mean Sq"].AsNumeric().ToArray();

Created Unassigned: "uniroot" function not found error [183]

$
0
0
Hello,

I am using RDotNet v1.6.5.0 on 64-bit windows. I am using some "thetaEst" function from "catR" package which uses "uniroot" (from stats package -it is a default package) function internally.

```
code I was trying : "library(catR);x=thetaEst(it=c(1,0,0,1),x=0))"
```
As web form application it worked fine. But when I used it under IIS it was throwing an error saying "unirrot function not found". Then I tried

```
code I was trying : "library(catR);library(stats)l;x=thetaEst(it=c(1,0,0,1),x=0))"
```

Then "stats" package failed to load" error was thrown.

But when I set Enable 32-Bit Applications to "True" it worked fine.

How can I make it work for without setting 32-bit Applications to "True" i.e. for 64-bit Applications?

New Post: R in WCF and return large set of Data

$
0
0
Hello,
I have an issue with my R.NET use in WCF services.

Scenario:
  1. Application client send data to WCF service
  2. WCF :
    a-convert data to DataFrame
    b-call R script (result as DataFrame)
    c-convert Dataframe to Object and return it
  3. Client get the result
It works great with small quantity of data (100 rows, 50 columns).

But with a large collection (Dataframe with 5000 rows, 50 columns) the application Pool of WCF (hosted in IIS) crash at the end of the execution (during returning data (after step 2.c)

Anyone have an idea of my problem?
There is any know issue using WCF with r.net ?

Thanks in advance,
Thibaud





In the event viewer:
Faulting application name: w3wp.exe, version: 7.5.7601.17514, time stamp: 0x4ce7afa2
Faulting module name: R.dll, version: 3.22.3517.0, time stamp: 0x55cdbbac
Exception code: 0xc00000fd
Fault offset: 0x0000000000023091
Faulting process id: 0x17c8
Faulting application start time: 0x01d14e2c7db0a182
Faulting application path: c:\windows\system32\inetsrv\w3wp.exe
Faulting module path: C:\R\bin\x64\R.dll
Report Id: f8982ba6-ba1f-11e5-a251-00155d8378f6


Example of my WCF service
 public class ComputeService : IOptimizationService
    {
        private REngine _engine;

        public ComputeService()
        {
        }

        public OutputData Launch(InputData input)
        {
            try
            {
               Log.Init("ApplicationLogger", LogLevel.Debug);
               Log.Debug("Launch Compute service");

               Log.Debug("Init R");
               // Init R.net library
               REngine.SetEnvironmentVariables();
               _engine = REngine.GetInstance();
               _engine.Initialize();

               Log.Debug("Load R script");

               // Script R path
               _engine.Evaluate("source('D:\myScripts')");

               //Preparing data to be passed to R .Net
               Log.Debug("Create demands dataframe");
               DataFrame myDataFrame = input.ToDataFrame(_engine);

               //R execution
               var optimizationRFunction = _engine.Evaluate("myFunction").AsFunction();

               Log.Debug("Launch R script");
               DataFrame optimizationResult = optimizationRFunction.Invoke(myDataFrame).AsDataFrame();
               Log.Debug("End R script");

               // //Result
               Log.Debug("Output : Begin");
               DataTable output = ConvertToDataTable(optimizationResult,"OptimizationResults");
               
               Log.Debug("End Compute service");
               
                // return data
                return output;
            }
            catch (Exception ex)
            {
                // check numero error
                // Manage type of faultException
                Log.Error(ex);
                throw new FaultException(ex.Message);
            }
        }
    }

New Post: R in WCF and return large set of Data

$
0
0
There is no obvious cause that I can see. A couple of suggestions you may consider to further diagnose the problem:
  • Is running functionally the same code in a single process (no WCF, no IIS) reproducing the issue.
  • Compile in debug mode and attach the running process executing ComputeService to Visual Studio, to get more information in inspect the call stack to get more information.

New Post: R in WCF and return large set of Data

$
0
0
Thank you for your feedback.

Yesterday, we have tested in Console App, and it working normaly.

So we test to use our WCF self hosted (in console App).
And the result was good. No crash, console app continue to work. No problem after several calls of the service.

I think IIS perform some actions on the memory.
Finally we keep Self hosted solution (We can also try to use Windows Services host)

Regards,
Thibaud

New Post: Call R script in UI thread crash the app

$
0
0
I am building an application which display a data table and allow user to define computed fields which the help of R functions. E.g., calculate the squreroot of one numeric field, and display the data table and the computed fields. However, it only works on the initial view, and crash when scroll or update the view. Below is a snippet (I am use WCF but it happen with WinForm).
XAML:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" Closing="Window_Closing"
      >
  <Grid>
    <DataGrid x:Name="dataGrid"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.VerticalScrollBarVisibility="Visible" PreviewKeyDown="dataGrid_PreviewKeyDown" />

  </Grid>
</Window>
And the code
using RDotNet;
using RDotNet.Devices;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfApplication1
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
    public static REngine engine;
    public class RValue
    {
      private int value;
     
      public RValue(int value)
      {
        this.value = value;
       }
      public int OriginValue
      {
        get { return value; }
      }

      public double SqrtValue
      {
        get
        {
          string script = "value<-" + value + ";" + "sqrt(value);";
          double rvalue = 0;
            rvalue = MainWindow.engine.Evaluate(script).AsNumeric().First();
          return rvalue;
        }
      }
    }
    public MainWindow()
    {
      InitializeComponent();
      REngine.SetEnvironmentVariables();
      engine = REngine.GetInstance();
      
      engine.Initialize();
     
      List<RValue> values = new List<RValue>(300);
      for (int i = 0; i < 300; i++)
      {
        values.Add(new RValue(i));
      }
      this.dataGrid.ItemsSource = values;
    }

    private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }
    ScrollViewer _scrollViewer = null;
    private void dataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
    {
      if (_scrollViewer == null)
      {
        _scrollViewer = GetVisualChild<ScrollViewer>(this.dataGrid);
      }
      switch (e.Key)
      {
        case Key.PageUp:
          _scrollViewer.PageUp();
          e.Handled = true;
          break;
        case Key.PageDown:
          _scrollViewer.PageDown();
          e.Handled = true;
          break;
      }

    }
    static T GetVisualChild<T>(Visual parent) where T : Visual
    {
      T child = default(T);
      int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
      for (int i = 0; i < numVisuals; i++)
      {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
          child = GetVisualChild<T>(v);
        }
        if (child != null)
        {
          break;
        }
      }
      return child;
    }
  }
}
The exception is "An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll and wasn't handled before a managed/native boundary

Additional information: Dispatcher processing has been suspended, but messages are still being processed."
 get
        {
          string script = "value<-" + value + ";" + "sqrt(value);";
          double rvalue = 0;
          var op = Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => rvalue = MainWindow.engine.Evaluate(script).AsNumeric().First()));
          if (op.Status !=  DispatcherOperationStatus.Completed)
          {
            op.Wait(new TimeSpan(100));
          }
           
          return rvalue;
        }
But it still crash on op.Wait. Have anyone used R.net with WPF or WinForm?

Created Unassigned: An unhandled exception of type 'System.InvalidOperationException' occurred in RDotNet.dll [184]

$
0
0
CODE :
using RDotNet;
...
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance();

ISSUE : header +
"Additional information: The single REngine instance has already been disposed of (i.e. shut down). Multiple engine restart is not possible."

W10 - VSTO 2015 Community - x64 - C# - RDotNet 1.6.5.0
Register : HKEY_LOCAL_MACHINE / SOFTWARE / R-Core / R/ R64 (/ 3.2.2)/ 3.2.3 (/ 8.0.3)
Check : registryKey.GetValue("InstallPath") ="C:\\Program Files\\R\\R-3.2.3"

On this environment, I have the issue but not on another computer (W7-R32-3.2.3).
Du you have solution ?

Edited Unassigned: An unhandled exception of type 'System.InvalidOperationException' occurred in RDotNet.dll [184]

$
0
0
CODE :
using RDotNet;
...
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance();

ISSUE : header +
"Additional information: The single REngine instance has already been disposed of (i.e. shut down). Multiple engine restart is not possible."

W10 - VSTO 2015 Community - x64 - C# - RDotNet 1.6.5.0
Register : HKEY_LOCAL_MACHINE / SOFTWARE / R-Core / R/ R64 (/ 3.2.2)/ 3.2.3 (/ 8.0.3)
(Check : RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\R-core\R");
registryKey.GetValue("InstallPath") ="C:\\Program Files\\R\\R-3.2.3")

On this environment, I have the issue but not on another computer (W7-R32-3.2.3).
Du you have solution ?

Edited Unassigned: An unhandled exception of type 'System.InvalidOperationException' occurred in RDotNet.dll [184]

$
0
0
CODE :
using RDotNet;
...
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance();

ISSUE : header +
"Additional information: The single REngine instance has already been disposed of (i.e. shut down). Multiple engine restart is not possible."

W10 - VSTO 2015 Community - x64 - C# - RDotNet 1.6.5.0
Register : HKEY_LOCAL_MACHINE / SOFTWARE / R-Core / R/ R64 (/ 3.2.2)/ 3.2.3 (/ 8.0.3)
(Check : RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\R-core\R");
registryKey.GetValue("InstallPath") ="C:\\Program Files\\R\\R-3.2.3")

On this environment, I have the issue but not on another computer (W7-R32-3.2.3).
Do you have a solution ?

New Post: Could Not Find Function "sd" Error in C#

$
0
0
I Develop a Simple program using RDotNet in C#.

I got "sd" function not found error. Can you give me some tips for solve this problem?

function "sd" is in "stats" package that is default library.

I already reinstall R(R-3.1.0-win.exe) again and again.

attached Error message and code as below.

"Error: could not find function "sd"
at RDotNet.REngine.Parse(String statement, StringBuilder incompleteStatement)
at RDotNet.REngine.<Defer>d__0.MoveNext()
at System.Linq.Enumerable.LastOrDefault[TSource](IEnumerable`1 source)
at RDotNet.REngine.Evaluate(String statement)"

The code as follow:
NumericVector group1 = regine.CreateNumericVector(examples);
regine.SetSymbol("group1",group1);

NumericVector STDResult = regine.Evaluate("sd(group1)").AsNumeric();

double[] arrSTD = STDResult.ToArray();
STD = arrSTD[0];
Thanks a lot.

New Post: Could Not Find Function "sd" Error in C#

$
0
0
you need to let the engine know you are intending to use the stats library.

add :
rengine.Evaluate("library(stats)");
prior to STDResult.

New Post: How can i load a package like forecast?

$
0
0
not sure exactly where your code is throwing the error.
But typically when i'm not sure if a package is installed or not I use the following check.

rengine.Evaluate("if("fastcluster" %in% rownames(installed.packages()) == FALSE) {install.packages("fastcluster")}");
rengine.Evaluate("library(fastcluster)");

Granted, I'm wanting to make sure that the fastcluster package is installed. Change fastcluster to forecast for your case.

New Post: Better way to capture plot image from R engine

$
0
0
I am attempting to capture the image from the console window using the following:
engine.Evaluate(string.Format("dev.copy(jpeg,'{0}')", rfilename));
the file is successfully saved.

But I'd like to capture the image without having the console window appear at all.

If I set the StartupParameter Interactive to false when initializing my engine, the console window doesn't appear but I'm also not able to capture the image.

Can someone point me to a project or code snippet that may help me capture the image created by an evaluation of the engine without having the console window pop open.

current example calls :
engine.Evaluate("hist(SiteData2$AVGOfSiteLatitude)");
or
engine.Evaluate("plot(SiteData2)");

Thank you in advance

Created Unassigned: IIS 10 deploy Rdotnet Issue [185]

$
0
0
Hi All,

I am facing deployment issues in IIS 10
__Error in library(RODBC) : there is no package called 'RODBC' same with other packages also__.
Anyhow this error automatically fixed on server but now another error is coming on server

__Error in sqlFetch(odbcChannel, "prices") :
first argument is not an open RODBC channel
__

Tried changing path also but nothing works for me
But in VS2015 its working fine

Thanks

Edited Unassigned: IIS 10 deploy Rdotnet Issue [185]

$
0
0
Hi All,

I am facing deployment issues in IIS 10
__Error in library(RODBC) : there is no package called 'RODBC' same with other packages also__.
Anyhow this error automatically fixed on server but now another error is coming on server

__Error in sqlFetch(odbcChannel, "prices") :
first argument is not an open RODBC channel__

Tried changing path also but nothing works for me
But in VS2015 its working fine

Thanks

New Post: Please help a new users

$
0
0
Hello,

I am trying to run a test program on my Windows 10 Enterprise (x64) machine.
I copied the following example into a new Console project (Visual Studio 2015):
  using System;
  using System.Linq;
  using RDotNet;

  namespace TestRDotNet {
    class Program {
      static void Main() {
        // REngine.SetEnvironmentVariables();
        // There are several options to initialize the engine, but by default the following suffice:
        var engine = REngine.GetInstance();

        // .NET Framework array to R vector.
        var 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.
        var 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.
        var testResult = engine.Evaluate("t.test(group1, group2)").AsList();
        var 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);

        // you should always dispose of the REngine properly.
        // After disposing of the engine, you cannot reinitialize nor reuse it
        engine.Dispose();
      }
    }
  }
I also installed the following package:


PM> Install-Package R.NET.Community
Attempting to gather dependencies information for package 'R.NET.Community.1.6.5' with respect to project 'TestRDotNet', targeting '.NETFramework,Version=v4.5.1'
Attempting to resolve dependencies for package 'R.NET.Community.1.6.5' with DependencyBehavior 'Lowest'
Resolving actions to install package 'R.NET.Community.1.6.5'
Resolved actions to install package 'R.NET.Community.1.6.5'
Adding package 'R.NET.Community.1.6.5' to folder 'C:\sm\Misc\TestRDotNet\packages'
Added package 'R.NET.Community.1.6.5' to folder 'C:\sm\Misc\TestRDotNet\packages'
Added package 'R.NET.Community.1.6.5' to 'packages.config'
Successfully installed 'R.NET.Community 1.6.5' to TestRDotNet

The test program compiled without any errors or warning messages.

When I tried to run the program, I got the following run-time error on the first line:

var engine = REngine.GetInstance();

The error message was:

System.ApplicationException was unhandled
HResult=-2146232832
Message=Windows Registry key 'SOFTWARE\R-core' not found in HKEY_LOCAL_MACHINE nor HKEY_CURRENT_USER
Source=RDotNet.NativeLibrary
StackTrace:
   at RDotNet.NativeLibrary.NativeUtility.GetRCoreRegistryKeyWin32(StringBuilder logger)
   at RDotNet.NativeLibrary.NativeUtility.FindRHome(String rPath, StringBuilder logger)
   at RDotNet.NativeLibrary.NativeUtility.FindRPaths(String& rPath, String& rHome, StringBuilder logSetEnvVar)
   at RDotNet.NativeLibrary.NativeUtility.SetEnvironmentVariables(String rPath, String rHome)
   at RDotNet.REngine.SetEnvironmentVariables(String rPath, String rHome)
   at RDotNet.REngine.GetInstance(String dll, Boolean initialize, StartupParameter parameter, ICharacterDevice device)
   at TestRDotNet.Program.Main() in C:\sm\Misc\TestRDotNet\TestRDotNet\Program.cs:line 10
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Any help will be greatly appreciated.

Charles

New Post: Please help a new users

$
0
0
Charles,

Did you install R on your machine also?

RDotNet will not function w/o the R application being installed on your machine.

If you haven't already downloaded it .. it's available from one of the mirrors

https://cran.r-project.org/mirrors.html

Created Unassigned: Connecting to R from C# using RDotNet unsuccessful from Forms application, but runs in console application [186]

$
0
0


I copied the example script (https://rdotnet.codeplex.com/) to a simple forms application, and it crashed on the REngine engine = REngine.GetInstance(); line giving the error message An unhandled exception of type 'RDotNet.EvaluationException' occurred in RDotNet.dll Additional information: Error: could not find function "memory.limit"

When copying the same script into a Console application, it runs without error.

Using Visual Studio 2015, R 3.2.2, RDotNet.Community 1.6.5

New Post: RdotNet and R version 3.2.4

$
0
0
Has anyone else upgraded to R-3.2.4revised-win yet?

I'm getting an error when trying to SetEnvironmentVariables

REngine.SetEnvironmentVariables();

rCurrentVersionString from registry is coming back as "3.2.4 revised"

return new Version(rCurrentVersionStringFromRegistry); throwing system.format exception.

Any suggestions on a fix?

New Post: RdotNet and R version 3.2.4

$
0
0
I've been struggling for a few hours trying to look for a solution, and feeling a bit happy when I finally found someone with the same problem :D

What is the version of R that I should use for now since it seems that it's not functioning well with 3.2.4-revised?
Viewing all 1634 articles
Browse latest View live


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