【问题标题】:How to convert std::vector<std::vector<double>> to Rcpp::Dataframe or Rcpp::NumericMatrix如何将 std::vector<std::vector<double>> 转换为 Rcpp::Dataframe 或 Rcpp::NumericMatrix
【发布时间】:2014-05-26 07:48:55
【问题描述】:

我有一个std::vector&lt;std::vector&lt;double&gt;&gt;,我想将其转换为Rcpp::DataFrameRcpp::NumericMatrix

我目前的解决方案看起来像这样,它远非理想;它产生一个数字列表。

RcppExport SEXP Foo(...)
{
    std::vector<std::vector<double>> result;

    /// ... Do some work.

    return Rcpp::wrap(result);
}

注意事项:列数和行数不会固定。在每次运行之间,这些都可以改变。我之所以提到这一点,是因为到目前为止我发现的许多解决方案都涉及在编译时了解列。

如果可能,我希望将解决方案完全包含在 c++ 中;即 R 用户应该能够调用该函数,而不必将结果手动处理到数据框或矩阵中。

【问题讨论】:

    标签: c++ r rcpp


    【解决方案1】:

    一般来说,将std::vector&lt;std::vector&lt;double&gt;&gt; 转换为列表是我们能提供的最好的方法。 DataFrame 要求所有列的长度相同。

    您必须自己手动处理。像这样制作矩阵:

    std::vector<std::vector<double>> result ;
    int nc = result.size(), nr = result[0].size() ;
    NumericMatrix m( nr, nc ) ;
    for( int j=0; j<nc; j++){
        std::vector<double>& result_j ;
        if( result_j.size() != nr ) stop( "incompatible size" ) ;
        for( int i=0; i<nr; i++){
            m(i,j) = result_j[i] ;
        }
    }
    

    直接制作DataFrame有点困难,我建议先制作一个列表,然后将此列表转换为DataFrame

    List list( nc ) ;
    for( int j=0; j<nc; j++) list[j] = wrap( result[j].begin(), result[j].end() ) ;
    DataFrame df = list ;
    

    您可能需要先设置列表的名称,然后再将其设为数据框。

    【讨论】:

    • 感谢您的建议。我选择了您提供的 NumericMatrix 解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2020-02-19
    • 1970-01-01
    • 2016-03-31
    • 2018-09-23
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多