【问题标题】:How to get a dataframe from R to C# using RserveCLI2如何使用 RserveCLI2 从 R 获取数据帧到 C#
【发布时间】:2018-04-25 08:09:08
【问题描述】:

我正在尝试使用包RServeCLI2 将数据帧从 R 环境获取到 C#。我似乎无法找到正确的方法。应该没那么难。

在 C# 中我做到了:

using System;
using RserveCLI2;

class TestMain
{
         public static void Main(string[] args)
         {
            var r = RConnection.Connect(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }), port: 6311);

            r.VoidEval("options(stringsAsFactors = FALSE)");
            r.VoidEval("samplePOSIXct <- as.POSIXct(c('2018-03-28 01:45:00', '2018-03-23 02:00:00', '2018-03-22 03:00:00'))");
            r.VoidEval("sampleDate <- as.Date(c('2018-03-24', '2018-02-05', '2018-01-30'))");
            r.VoidEval("sampleLogical <- as.logical(c(TRUE, FALSE, FALSE))");
            r.VoidEval("sampleNumeric <- as.numeric(c(1,NA,5))");
            r.VoidEval("sampleCharacter <- as.character(c('ik', 'wil', 'bolletje'))");
            r.VoidEval("df <- data.frame(samplePOSIXct, sampleDate, sampleLogical, sampleNumeric, sampleCharacter)");

            Sexp dataset = r["df"];

            for (int rows = 0; rows < dataset.Attributes.Count; rows++)
            {
                for (int cols = 0; cols < dataset.Names.Length; cols++)
                {
                    Console.WriteLine(string.Format("Col: {0}, Row: {1}",
                        dataset.Names[cols], dataset.AsDictionary[dataset.Names[cols]]));
                }
            }
            var exit = Console.ReadLine();
         }
}

这运行成功,但结果不是我想要的。每次调用都会打印所有行。结果:

#Col: samplePOSIXct, Row: 1522194300 1521766800 152168400
#Col: sampleDate, Row: 24-03-2018 05-02-2018 30-01-2018
#...

我怎样才能得到这样打印的值?

#Ideal output
#Col: samplePOSIXct Row: 1522194300
#Col: samplePOSIXct Row: 1521766800
#Col: samplePOSIXct Row: 1521684000
#Col: sampleDate Row: 24-03-2018
#...

【问题讨论】:

    标签: c# r dataframe rserve


    【解决方案1】:

    我找到了答案,这可能是一个 hacky 的答案,但我对此感到满意。我在第一个循环中提取了数据帧的每一列,将其放入IList&lt;object&gt;,然后在第二个循环中提取每个值。

    //...
    Sexp dataset = r["df"];
    
    for(int cols = 0; cols < dataset.Names.Length; cols++)
    {
        IList<object> datasetL = r[$"df[,{cols + 1}]"].AsList;
        for(int rows = 0; rows < dataset.Attributes.Count; rows++)
        {
            Console.WriteLine($"Col: {dataset.Names[cols]}, Row: {datasetL[rows].ToString()}");
        }
    
    }
    //...
    
    #Results
    #Col: samplePOSIXct, Row: 1522194300
    #Col: samplePOSIXct, Row: 1521766800
    #Col: samplePOSIXct, Row: 1521684000
    #Col: sampleDate, Row: 17614
    #...
    

    如果有人知道更好的答案(为了提高效率),我愿意接受

    【讨论】:

      猜你喜欢
      • 2017-01-28
      • 2021-03-08
      • 2022-01-03
      • 2020-05-21
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      相关资源
      最近更新 更多