Error: Unable to convert using R function: as.data.frame

I am trying to read a text file in C ++ and return it as a DataFrame. I created a skeleton method to read a file and return it:

// [[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;
}

      

I am running in R using:

> df <- rcpp_hello_world( "my_haproxy_logfile" )

      

However, R returns the following error:

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

      

What am I doing wrong?

Many thanks.

+3


source to share


1 answer


DataFrame objects are "special". Our preferred use is through return Rcpp::DateFrame::create ...

, which you'll see in many examples posted, including numerous answers here.

Here is one from the 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);
}

      

Focused on modifying the DataFrame, it shows you how to create it. The label _["a"]

can also be written as Named("a")

which I prefer.

+5


source







All Articles