Posted by: joachimvandenbogaert | March 26, 2009

R and C# on Windows

The following page offers a good introduction, but some information is missing. So I thought it would be useful to add some more instructions, especially for deployment on client systems on which R has not been installed yet.

http://www.codeproject.com/KB/cs/RtoCSharp.aspx

Here’s a list of issues:

  1. R requires Administrator rights when you install it (as described in the R Administration guide). This also applies when you want to install add-ons. R itself does not have these permissions, so if you install an add-on from within R, you will get an “access denied” error (to install an add-on, you can use the R gui,  Packages->Install package(s) …). A workaround is to make the R program directory writable to everyone. Maybe you can also try to run R itself as administrator when you need to install a package, but I haven’t tried this yet. This would probably be a better solution.
  2. Anyway, on windows, the install procedure is not actually an install procedure. You only get a zip file in a temporary directory. So to really install an add-on, you need to copy the extracted add-on folder and copy it to the Rlibrary. Note that this also requires write access to the R installtion folder.

Here’s a summary of what you need to do to get R working:

  1. Download the rscproxy package http://www.freestatistics.org/cran/bin/windows/contrib/r-release/rscproxy_1.2-0.zip, unzip it and install the rscproxy directory in your Rlibrary directory.
  2. Download R_Scilab_DCOM3.0-1B5.exe from http://www.freestatistics.org/cran/contrib/extra/dcom/R_Scilab_DCOM3.0-1B5.exe (you coulds also use another mirror), and install it.
  3. To use R, add a reference to your C# project to STATCONNECTORCLNTLib, StatConnectorCommonLib, and STATCONNECTORSRVLib (this is to get full functionality, for the client to work, you only need STATCONNECTORSRVLib).
  4. Use the STATCONNECTORSRVLib.StatConnectorClass to interface with R.

Here’s some example code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

//COM references
using STATCONNECTORCLNTLib;
using StatConnectorCommonLib;
using STATCONNECTORSRVLib;
using System.IO;

namespace RConnector.Tests.Integration
{
    [TestFixture]
   
public class TestConnectivityWithR
   
{


        [Test]
       
public void Open_Close()
       
{
           
StatConnectorClass RConnector = new StatConnectorClass();
            RConnector.Init(
“R”);
            RConnector.Close();
        }

        [Test]
       
public void Send_Receive_Data_()
       
{
           
StatConnectorClass RConnector = new StatConnectorClass();
            RConnector.Init(
“R”); 
          
// Data we are going to pass
           
int n = 20;
           
// Cast C# type to R type
           
RConnector.SetSymbol(“n1″, n); 
           
// The cast value n to n1 is now being used in R
           
RConnector.Evaluate(“x1 <- rnorm(n1)”); 
           
// We get back the value of x1, but it needs to be cast
           
// to an array of doubles
           
object o = RConnector.GetSymbol(“x1″);
           
double[] random = (double[])o;
           
foreach (double d in random)
            {
               
Console.WriteLine(d);
            }
        }

        [Test]
       
public void Plot_CSharpInput_Simple()
        {
           
StatConnectorClass RConnector = new StatConnectorClass();
            RConnector.Init(
“R”);
           
double[] input = new double[] { 1.0, 2.0, 3.0, 2.0, 1.0};
            RConnector.SetSymbol(
“input”, input);
            RConnector.EvaluateNoReturn(
“hist(input)”);
            RConnector.EvaluateNoReturn(
               
“savePlot(filename = \”” +
               
@”C:\\Users\\Joachim\\Documents\\Debug\\Plot_CSharpInput.eps” + “\”, ” + 
               
“type = \”eps\”, device = dev.cur(), restoreConsole = TRUE )”
           
); 
           
//RConnector.Close();
       
}
 
        [Test] public void Plot_CSharpInput_Simple_WithColors_Rainbow()
        {
            StatConnectorClass RConnector = new StatConnectorClass();
            RConnector.Init(“R”);
            double[] input = new double[] {1.0, 2.0, 3.0, 2.0, 1.0};
            RConnector.SetSymbol(“input”, input);
            RConnector.EvaluateNoReturn(“barplot(input, main=\”Foobar\”, xlab=\”Value\”, ylab=\”Frequency\”, col=rainbow(7))”);
            RConnector.EvaluateNoReturn(“legend(\”topleft\”, c(\”Hello\”, \”World\”), cex=0.6, bty=\”n\”, fill=rainbow(5))”);
            RConnector.EvaluateNoReturn(
                “savePlot(filename = \”” +
                @”C:\\Users\\Joachim\\Documents\\Debug\\Plot_CSharpInput.eps” + “\”, “ +
                “type = \”eps\”, device = dev.cur(), restoreConsole = TRUE )”);
            //RConnector.Close();
        }
    }
}
About these ads

Responses

  1. [...] ya estas en algo con todo esto debes entrar a ejemplos mas avanzado -> http://joachimvandenbogaert.wordpress.com/2009/03/26/r-and-c-on-windows/ [...]

  2. hey its not coming together. i have downloaded .net SDK 2.0 and R version 2.9.2 . the server file is R_Scilab_DCOM3.0-1B5.exe. but then when i try to use the classes as u have used they dont compile in c# giving error 0246: the type or namespace cannot be found. are u missing a using directive or an assembly reference ?

  3. The example here uses NUnit as a a testing framework. Are you sure you added a reference to the nunit.framework.dll? If not, download NUnit, install it and add a reference to the framework dll (you will also need this for the [TestFixture] and [Test] attributes). Please let me know if this is not the problem, the I wil look into it.

    • it still doesn’t work. in fact the other link which u have provided at the top has some simpler examples and even they dont work. i work with c# in the command prompt. is there anyway i can do it ? the basic question i guess is that i am not being able to link the library files that u have mentioned as i am not being able to find them. the samples work fine as provided by the (D)COM but its the linking part which is creating problems. please do help me out as i am in an urgent need . thnx

  4. THANKS for the code!

    I needed to make a few changes but overall I would say that this is a nice demonstration of C# talking to R. Nice Histograms!

    Here is my altered code (using a Main()) entry point.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using NUnit.Framework;

    //COM references
    //using Interop.STATCONNECTORCLNTLib;
    using StatConnectorCommonLib;
    //using STATCONNECTORSRVLib;
    using System.IO;
    using Interop.STATCONNECTORSRVLib;

    namespace RConnector.Tests.Integration
    {

    //===============================================
    class MainEntryPoint
    {
    static void Main()
    {
    TestConnectivityWithR.Open_Close();
    TestConnectivityWithR.Send_Receive_Data_();
    TestConnectivityWithR.Plot_CSharpInput_Simple();
    TestConnectivityWithR.Plot_CSharpInput_Simple_WithColors_Rainbow();
    }

    }

    }
    //=========================================================
    // [TestFixture]
    public class TestConnectivityWithR
    {

    // [Test]

    public static void Open_Close()
    {
    Interop.STATCONNECTORSRVLib.StatConnectorClass RConnector = new Interop.STATCONNECTORSRVLib.StatConnectorClass();
    RConnector.Init(“R”);
    RConnector.Close();
    Console.ReadLine();
    }

    // [Test]
    // public static void Main()
    public static void Send_Receive_Data_()
    {
    Interop.STATCONNECTORSRVLib.StatConnectorClass RConnector = new Interop.STATCONNECTORSRVLib.StatConnectorClass();
    RConnector.Init(“R”);
    // Data we are going to pass
    int n = 20;
    // Cast C# type to R type
    RConnector.SetSymbol(“n1″,n);
    // The cast value n to n1 is now being used in R
    RConnector.Evaluate(“x1 <- rnorm(n1)");
    // We get back the value of x1, but it needs to be cast
    // to an array of doubles
    object o = RConnector.GetSymbol("x1");
    double[] random = (double[])o;
    foreach (double d in random)
    {
    Console.WriteLine(d);
    }
    Console.ReadLine();
    }
    // [Test]
    public static void Plot_CSharpInput_Simple()
    {
    Interop.STATCONNECTORSRVLib.StatConnectorClass RConnector = new Interop.STATCONNECTORSRVLib.StatConnectorClass();
    RConnector.Init("R");
    double[] input = new double[] { 1.0, 2.0, 3.0, 2.0, 1.0};
    RConnector.SetSymbol("input", input);
    RConnector.EvaluateNoReturn("hist(input)");
    RConnector.EvaluateNoReturn(
    "savePlot(filename = \"" +
    @"F:\\WEBSITE\\Plot_CSharpInput.eps" + "\", " +
    "type = \"eps\", device = dev.cur(), restoreConsole = TRUE )"
    );
    Console.ReadLine();
    RConnector.Close();
    }

    // [Test]
    // public static void Main()
    public static void Plot_CSharpInput_Simple_WithColors_Rainbow()
    {
    Interop.STATCONNECTORSRVLib.StatConnectorClass RConnector = new Interop.STATCONNECTORSRVLib.StatConnectorClass();
    RConnector.Init("R");
    double[] input = new double[] {1.0, 2.0, 3.0, 2.0, 1.0};
    RConnector.SetSymbol("input", input);
    RConnector.EvaluateNoReturn("barplot(input, main=\"Foobar\", xlab=\"Value\", ylab=\"Frequency\", col=rainbow(7))");
    RConnector.EvaluateNoReturn("legend(\"topleft\", c(\"Hello\", \"World\"), cex=0.6, bty=\"n\", fill=rainbow(5))");
    RConnector.EvaluateNoReturn(
    "savePlot(filename = \"" +
    @"F:\\WEBSITE\\Plot_CSharpInput.eps" + "\", " +
    "type = \"eps\", device = dev.cur(), restoreConsole = TRUE )");

    Console.ReadLine();
    RConnector.Close();
    }

    }

  5. Thanks for this code!

    I am new to C# and wanted to utilise my R code. This will really help!!!

  6. I’m recieving the following error

    Test method TestProject1.UnitTest1.Open_Close threw exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040013.

    It seams that C# can’t initialize R via the COM Interface. Do the C# binaries have to reside in the R path?

  7. Hi there.
    I’ve got it all working on Win XP, but I can’t get it to work on Windows 7. I’ve tried this and many other solutions given out there.
    Do you know anything about it with Windows 7??
    Thanks

    • Hi, it’s nice to hear that you got it working. I haven’t had the chance to install Windows 7 yet. But I’m expecting to do so by the end of this month. I’ll keep you posted.

  8. It works fine on 64 bit win7. Visual Studio 2008 with C#.

    • Really? I also have the 64bits version of Win7 with VS2008 SP1.
      When I try to connect it throws an Exception, some RPC error.
      I noticed that, when opening the RDCOM Manager, no service is listed. However, a StatConnectorSrv.exe process shows up in the task manager, but whenever I try to connect or create a new one through the manager, it stops.
      I have no idea :(

  9. Hello there,
    i have the same problem with Windows 7. When i start your code, no eps file is cerated. If i change the saveplot method to jpeg, then an error occured :-(

  10. Hi,
    I’m trying to get to work R with C# too with the same method described in this page.
    I’m using C# code inside Ninja trade, which is a trading platform that provides an integrated C# enviroment.

    My problem is that I can’t add a reference to STATCONNECTORCLNTLib, StatConnectorCommonLib, and STATCONNECTORSRVLib in my C# class.

    I get error message “Incorrect format” when I try to add a reference to the StatConnectorClnt.dll library in “C:\Program Files\R\(D)COM Server\bin”

    any idea?

  11. Hello, I installed all the tools that is necesary to run R form C#, but when I try to run this code:

    StatConnector sc1 = new STATCONNECTORSRVLib.StatConnectorClass();
    try {
    sc1.Init(“R”);
    sc1.Evaluate(“a <- c(0,1,0,1,0,1,0,1,0,1)");
    sc1.Evaluate("b = c(1,2,3,4,5,6,7,8,9,10)");

    object a = sc1.GetSymbol("a");
    object b = sc1.GetSymbol("b");

    //sc1.Evaluate("modelo = glm(a ~ b, family='binomial')");
    sc1.Evaluate("modelo = lm(a ~ b)");
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.Message);
    Console.WriteLine(sc1.GetErrorId() + " – " + sc1.GetErrorText());
    }

    The code throws this exception: "There is no connection for this connection ID (Exception from HRESULT: 0x80040004 (OLE_E_NOCONNECTION))".
    Anyone know why this happend?

    Thanks.

  12. you need to Download the rscproxy package and install it to work with c#

  13. Hi,
    Thanks for the code!
    But I have another problem. How to use the functions in the extended package? For example:
    I want to draw a histogram which can interact with users using the “ihist(x)” function in package “iplot”, do I have to load the package “iplot” through c# code first? How can I do this ?
    My email: yiyeqiu.6162714@163.com
    Thanks

  14. I posted a couple of blog posts on the same lines which you might find useful …

    http://vvella.blogspot.com/2010/08/integrate-c-net-and-r-taking-best-of.html

  15. How to kill the R session that is initiated in the taskmanager. After using RConnector.init(“R”)..the session is hanging even after using RConnector.close. Please advise

  16. I am getting an exception when calling Init(“R”);

    Exception from HRESULT: 0x80040013

  17. so great post!

  18. [...] http://joachimvandenbogaert.wordpress.com/2009/03/26/r-and-c-on-windows/ [...]

  19. I’ve been able to use R in C# on my machine by following the steps on this blog. Thanks !

    This works locally, i.e. if R is running on my box. What if I can connect to another machine that is running R (and has rscproxy installed). How can I change the code above to specify what machine to connect to ?

    This way a lot of people can use R without having to first install it on their boxes.

  20. Hi,

    I am trying to connect R to C# (vs 2008) ON Win 7 64 bit..but no matter what I do I still get Exception from HRESULT: 0x80040013 at the code line with Init(“R”)..
    I tried RAndFriends, 3 different versions, then I tried to install separately R and COM Server, rscproxy…nothing works..As far as I have read the previous comments …it should work on Windows 7..Does anyone have any clue?

  21. Hi all,

    I migrated some time ago to Java, but since I keep getting responses on this post, I will be keeping an eye on it. Thanks for all the feedback.

  22. Dim Sc1 As New StatConnectorClass()
    Sc1.Init(“R”)
    Sc1.Evaluate(“library (RODBC)”)
    Sc1.EvaluateNoReturn(“cn<-odbcConnect(""DSN_server"",""sa"",""password"")")
    Sc1.EvaluateNoReturn("x<-sqlQuery(cn, paste(""select * from Product""))")
    Sc1.Evaluate("x")

    In above, I didnt get Ans in X, I what whole output in Table/Array format…
    Can you hele me in it.

  23. You can also check the new R.NET project at CodePlex. No (D)COM (just R.DLL interop.), no installation and very fast, but still under development. Free for commercial use, sources are available. Remember to compile the DLL from the newest sources!

    Project site: http://rdotnet.codeplex.com

    Some additional info about display plots: http://rdotnet.codeplex.com/workitem/7

  24. I was having similar errors attempting to add the .dll from the R install files or R server install. This cleared it up:

    “From the solution explorer add reference to the R (D)COM library. In the COM components list you typically find the component name listed as ‘Repository for R COM Server Instances’.”

    Source: http://vvella.blogspot.com/2010/08/integrate-c-net-and-r-taking-best-of.html

  25. Hello, I am using the StatConnector class in an MVC3 project to repeatedly call an R function in response to a user gesture on the browser. I’m having difficulty in persisting the instantiated object so as to avoid instantiating a new one every time I call the function. ASP.NET is stateless, so I’ve tried storing the object at the Application level, in the Cache, and have declared it as a static variable, all with no luck. I keep getting the following error message upon the 2nd attempt to use the static instance of StatConnector:

    There is no connection for this connection ID (Exception from HRESULT: 0x80040004 (OLE_E_NOCONNECTION))

    Exception Details: System.Runtime.InteropServices.COMException: There is no connection for this connection ID (Exception from HRESULT: 0x80040004 (OLE_E_NOCONNECTION))

    Any help would be very greatly appreciated. Basically I just want to keep the instance live across multiple requests so that the application performs optimally.

  26. Hi. I am getting the error which most ppl are facing. That is System.Runtime.InteropServices.COMException,RESULT: 0x80040013.

    I am trying to reference 3 COM libraries: StatConnectorClnt 1.0 type library,StatConnectorCommon 1.3 Type Library and StatConnectorSrv 1.1 Type Lirbary. Please someone refer how can i resolve this error

  27. Hi
    Isn’t there any way to run the R script file from C#? I’ve a complete program in R, just I want to execute R script file from C#.
    anyone who knows this plz let me know

  28. How to run nested loops of R from C#?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: