~ Hayward's blog on psychology, visual cognition, and stats

Importing and displaying a Data frame with C# and R.NET

In this post, I give a brief and basic example of how to import a file into R and then display it using a C#-based windows GUI.

Background

I’ve previously put up an introduction to getting C# and windows-based GUI programs to interact with R using R.NET. My previous example was very, very basic (just a calculator talking to R), so here’s something that’s a little bit more interesting.

The end result looks something like this, with a dataset I used in previous examples imported from a CSV file:

The ‘Import CSV file’ button calls up the function that does the work.

We then send a simple command to R as we would if we wanted to import a CSV file, using the read.table command. The useful thing here is that I’ve used file.choose() which is helpful because it creates the popup dialog window you’d expect from R to help you choose the file to import. Note that I’ve set it here to import a CSV, but of course you could change this to any of the other many formats your data may be in.

DataFrame dataset = engine.EagerEvaluate("dataset").AsDataFrame();

Once we have chosen our file, we need to get the dataframe back from R so we can then display it in a DataGridView box (here called dataGridView1). To work out how to do that, we just ask oursevles the question: how would we do it using R? We’d just type in the dataframe’s name – which, in this case, is dataset. To send this command to R from R.NET, you just need to use engine.eagerevaluate. This sends the command “dataset” to R running in the background as though we were typing it into the console ourselves.

Now, we next need to tell R.NET what to do with the command we’ve just sent it. We’ve asked for a dataframe, so we want to take the result we get from our command and convert it to a dataframe for R.NET to interact with. To do that, we just append AsDataFrame() at the end of the eagerevaluate command. We now have one dataframe in R called dataset, and one in our C# program also called dataset!

With our dataframe imported through from R, we can begin by building up our DataGridView box. It’s just a simple case of iterating through the dataframe we’ve created and filling the DataGridView box. R.NET has all the useful ways to interact with a dataframe that you would expect, including getting access to the number of rows and columns, as well as the names of those rows and columns. I begin by setting up the column names using the code above.

3 thoughts on “Importing and displaying a Data frame with C# and R.NET”

Glad it was helpful! If you’re going to use it, you may want to read this: http://rdotnet.codeplex.com/discussions/262846 . The currently available dll for R.NET has a problematic bug in it, so it’s best to use the latest version of the source code.