【问题标题】:Error: could not convert using R function : as.data.frame错误:无法使用 R 函数进行转换:as.data.frame
【发布时间】:2014-12-08 20:00:29
【问题描述】:

我正在尝试读取 C++ 中的文本文件并将其作为 DataFrame 返回。我创建了一个用于读取文件并返回它的骨架方法:

// [[Rcpp::export]]
DataFrame rcpp_hello_world(String fileName) {

    int vsize = get_number_records(fileName);
    CharacterVector field1 = CharacterVector(vsize+1);

    std::ifstream in(fileName);

    int i = 0;
    string tmp;
    while (!in.eof()) {
      getline(in, tmp, '\n');
      field1[i] = tmp;
      tmp.clear( ); 
      i++;
    }
    DataFrame df(field1);
    return df;
}

我在 R 中使用:

> df <- rcpp_hello_world( "my_haproxy_logfile" )

但是,R 返回以下错误:

Error: could not convert using R function : as.data.frame

我做错了什么?

非常感谢。

【问题讨论】:

    标签: r rcpp


    【解决方案1】:

    DataFrame 对象是“特殊的”。我们的首选用法是通过return Rcpp::DateFrame::create ...,您将在许多发布的示例中看到它,包括这里的许多答案。

    这是一个from a Rcpp Gallery post

    #include <Rcpp.h>
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    DataFrame modifyDataFrame(DataFrame df) {
    
      // access the columns
      Rcpp::IntegerVector a = df["a"];
      Rcpp::CharacterVector b = df["b"];
    
      // make some changes
      a[2] = 42;
      b[1] = "foo";       
    
      // return a new data frame
      return DataFrame::create(_["a"]= a, _["b"]= b);
    }
    

    虽然专注于修改 DataFrame,但它顺便向您展示了如何创建一个。 _["a"] 快​​捷方式也可以写成Named("a"),我更喜欢。

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2023-01-30
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多