Artiga Artiga - 2 months ago 41
R Question

How can I convert a data table in C# to data.fame in R using R.net

I need to convert a data table which I have defined as follows to a data frame in R.

DataTable dtb = new DataTable();
dtb.Columns.Add("Column1", Type.GetType("System.String"));
dtb.Columns.Add("Column2", Type.GetType("System.String"));
DataRow dtr1 = dtb.NewRow();
dtr1[0] = "abc";
dtr1[1] = "cdf";
dtb.Rows.Add(dtr1);
DataRow dtr2 = dtb.NewRow();
dtr2[0] = "asdasd";
dtr2[1] = "cdasdasf";
dtb.Rows.Add(dtr2);


Is there any way to convert above DataTable "
dtb
" to a data.frame in R.
I have defined this DataTable in C# but I need to do computation in R, that is why I need to pass it to R.

Answer

This worked in R.NET 1.6.5 and outputs:

output from console application

Did not find a nice way of converting DataTable to string[,] as CreateCharacterMatrix expects but CreateDataFrame is an alternative possibility but that expects a IEnumerable[] and is column oriented (as data.frame in R is).

Going through the Tests in the source code might help further: https://github.com/jmp75/rdotnet/tree/master/RDotNet.Tests

There is also this: https://github.com/jmp75/rdotnet-onboarding

Which is in some ways more helpful because the official documentation is sparse: https://jmp75.github.io/rdotnet/getting_started/

using System;
using System.Data;
using RDotNet;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dtb = new DataTable();
            dtb.Columns.Add("Column1", Type.GetType("System.String"));
            dtb.Columns.Add("Column2", Type.GetType("System.String"));
            DataRow dtr1 = dtb.NewRow();
            dtr1[0] = "abc";
            dtr1[1] = "cdf";
            dtb.Rows.Add(dtr1);
            DataRow dtr2 = dtb.NewRow();
            dtr2[0] = "asdasd";
            dtr2[1] = "cdasdasf";
            dtb.Rows.Add(dtr2);

            using (var engine = REngine.GetInstance())
            {
                string[,] stringData = new string[dtb.Rows.Count, dtb.Columns.Count];
                for (int row = 0; row < dtb.Rows.Count; row++)
                {
                    for (int col = 0; col < dtb.Columns.Count; col++)
                    {
                        stringData[row, col] = dtb.Rows[row].ItemArray[col].ToString();
                    }
                }
                CharacterMatrix matrix = engine.CreateCharacterMatrix(stringData);
                engine.SetSymbol("myRDataFrame", matrix);
                engine.Evaluate("myRDataFrame <- as.data.frame(myRDataFrame, stringsAsFactors = FALSE)");
                engine.Evaluate("str(myRDataFrame)");

            }
            Console.ReadKey();
        }
    }
}
Comments