Passing a DataTable through COM to R

I am trying to transfer data from SQL to C #, then to an R server for data analysis, then back to my web application; however, the COM interface that I use does not allow the transfer of complex data types between C # and R (there are no data tables). I got it to work in the past using the following code:

    int count = dataTable.Rows.Count;
    object[] y = new object[count];
    object[] x = new object[count];

    //R does not accept DataTables, so here we extract the data from
    //the table and pass it into 2 double arrays.
    for (int i = 0; i < count; i++)
    {
        y[i] = Convert.ToDouble(dataTable.Rows[i][0]);
        x[i] = Convert.ToDouble(dataTable.Rows[i][1]);
    }
    //Instantiate R connection
    StatConnector r = new STATCONNECTORSRVLib.StatConnectorClass();
    r.Init("R");
    r.SetSymbol("y", y);  //Passes column y into R
    r.SetSymbol("x", x);  //Passes column x into R

Now my problem arises from the fact that I'm no longer limited to just doubling, all that comes out of the SQL database is fair play (int, varchar, etc.), and that I no longer call only two data columns (this may, however, be indicated by many users).

How to convert data of dynamic sizes and dynamic data types into an array that can be safely transferred to rcom?

+3
2
+2

CSV. , RCOM: s !

public static string DataTableToCSV(DataTable myTable)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < myTable.Columns.Count; i++)
    {
        sb.Append("\"");
        sb.Append(myTable.Columns[i].ColumnName);
        sb.Append("\"");
        if (i < myTable.Columns.Count - 1)
            sb.Append(",");
    }
    sb.AppendLine();
    foreach (DataRow dr in myTable.Rows)
    {
        for (int i = 0; i < dr.ItemArray.Length; i++)
        {
            sb.Append("\"");
            sb.Append(dr.ItemArray[i].ToString());
            sb.Append("\"");
            if (i < dr.ItemArray.Length - 1)
                sb.Append(",");
        }
        sb.AppendLine();
    }
    return sb.ToString();
}
+2

Source: https://habr.com/ru/post/1752368/


All Articles