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:
- 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.
- 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:
- 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.
- 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.
- 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).
- 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);
}
}
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();
}
{
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();
}
}
[...] 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/ [...]
By: R Project for Statistical Computing + .net + BI - Joga's Blog on August 1, 2009
at 1:14 am
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 ?
By: sidmaestro on September 23, 2009
at 10:41 pm
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.
By: joachimvandenbogaert on September 24, 2009
at 8:54 am
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
By: sidharth on October 21, 2009
at 7:52 am
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();
}
}
By: rwillia2001 on December 5, 2009
at 8:16 pm
Thanks for this code!
I am new to C# and wanted to utilise my R code. This will really help!!!
By: Matt P-H on December 10, 2009
at 9:32 am
I’m recieving the following error
Test method TestProject1.UnitTest1.Open_Close threw exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0×80040013.
It seams that C# can’t initialize R via the COM Interface. Do the C# binaries have to reside in the R path?
By: GL on December 11, 2009
at 4:43 pm
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
By: Caerolus on December 31, 2009
at 3:18 pm
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.
By: joachimvandenbogaert on January 7, 2010
at 9:38 am
It works fine on 64 bit win7. Visual Studio 2008 with C#.
By: rwillia2001 on January 8, 2010
at 10:56 pm
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
By: Caerolus on January 11, 2010
at 7:27 pm
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
By: Slippy on February 15, 2010
at 5:24 pm
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?
By: Matteo on March 31, 2010
at 10:40 am
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: 0×80040004 (OLE_E_NOCONNECTION))".
Anyone know why this happend?
Thanks.
By: Leo on May 1, 2010
at 7:25 pm
you need to Download the rscproxy package and install it to work with c#
By: Tiago on May 31, 2010
at 2:16 am
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
By: Lily on August 1, 2010
at 7:27 am
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
By: Vince Vella on August 13, 2010
at 12:01 pm
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
By: december on October 13, 2010
at 10:10 am
I am getting an exception when calling Init(“R”);
Exception from HRESULT: 0×80040013
By: vanath on November 9, 2010
at 8:53 am
so great post!
By: ross on November 15, 2010
at 5:21 pm
[...] http://joachimvandenbogaert.wordpress.com/2009/03/26/r-and-c-on-windows/ [...]
By: Memanggil R dari C# on March 13, 2011
at 5:28 am
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.
By: Akhil on April 27, 2011
at 7:22 pm
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: 0×80040013 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?
By: Andra on May 6, 2011
at 8:53 am
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.
By: joachimvandenbogaert on May 6, 2011
at 9:03 am
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.
By: Nadir Riyani on May 31, 2011
at 8:55 am