Chris Snow
Chris Snow

Reputation: 24606

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

I'm trying to read a text file in C++ and return it as a DataFrame. I have created a skeleton method for reading the file and returning 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.

Upvotes: 3

Views: 1878

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368261

DataFrame objects are "special". Our preferred usage is via return Rcpp::DateFrame::create ... which you will see in many of the posted examples, including in the many answers here.

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

While focussed on modifying a DataFrame, it shows you in passing how to create one. The _["a"] shortcut can also be written as Named("a") which I prefer.

Upvotes: 5

Related Questions