错误:无法使用R函数转换:as.data.frame

Chr*_*now 3 r rcpp

我正在尝试用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;
}
Run Code Online (Sandbox Code Playgroud)

我在R中运行使用:

> df <- rcpp_hello_world( "my_haproxy_logfile" )
Run Code Online (Sandbox Code Playgroud)

但是,R返回以下错误:

Error: could not convert using R function : as.data.frame
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

非常感谢.

Dir*_*tel 5

DataFrame对象是"特殊的".我们的首选用法是return Rcpp::DateFrame::create ...您将在许多已发布的示例中看到的内容,包括此处的许多答案.

这是Rcpp Gallery帖子中的一篇:

#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);
}
Run Code Online (Sandbox Code Playgroud)

在专注于修改 DataFrame的同时,它向您展示了如何创建一个DataFrame._["a"]快捷方式也可以按Named("a")我喜欢的方式编写.