I'm writing a console app in C#, and I'd like to use the R engine to pop up a graph in a window.
Does anyone know if this is possible from Visual Studio 2012?
Yes, it is possible. What you need is to execute R code from C#. By searching on google I found the following project: The R Statistical Language and C#.NET: Foundations by Jeff B. Cromwell.
Here is some code to generate a histogram plot of twenty normal random variables:
//using STATCONNECTORCLNTLib;
StatConnector test1 = new StatConnectorClass();
test1.Init("R");
test1.Evaluate("x <- rnorm(20)");
test1.EvaluateNoReturn("hist(x)");
As said by others , R.net
is promising project (still unstable).
The philosophy behind is to manipulate R objects within .net framework.
I think if all what you want is to pop a graph in a window, it is better to create a.bat file where you call your R script using the very good Rscript
command.
Something like this should work for you:
In your c# side , you call
Process.Start("launcher.bat");
and you define your launcher.bat
:
PATH PATH_TO_R/R-version/bin;%path%
cd PATH_TO_R_SCRIPT
Rscript myscript.R arg1 arg2
To pull a graph from R into .NET, and display it on a WinForms panel:
First, we have to install Statconn, which is the bridge between .NET and R. Its important to install the correct version (it won't work if there is the wrong mix of x32 and x64). The easiest way to ensure this is to install Statconn from within the R console:
# Install Statconn bridge.
# Load the "rcom" package:
install.packages('rcom')
# Load the library 'rcom':
library('rcom')
At this point, it will give an error that you don't have the Statconn
library installed. This is easy to fix:
install.packages('statconn')
This will automatically install the correct version of the StatConn bridge, which is a standalone windows installer.
Now that we have installed Statconn, we can open up the sample .NET project in C:\Program Files (x86)\statconn\DCOM\samples\Graphics.NET
. This sample .NET project shows how to use R to plot graphics from within a C# WinForms project.
p.s. There is also other sample code for Python, C++, VBS, jscript, etc.
If you cannot get this working, try R.Net
, which is probably a better choice because Statconn hasn't been updated in a while, and is quite picky with less than perfect mixtures of '32-bit' / '64-bit' / 'supported R versions'.
The package R.net might be a good place to start looking at the results of a quick google. Alternatively, you could use a more basic approach by creating R scripts that can be called from the commandline, and use system calls from C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With