[Rcpp-devel] trouble creating a dataframe

Dirk Eddelbuettel edd at debian.org
Mon Jun 4 22:58:54 CEST 2012


Hi Pratibha,

On 4 June 2012 at 16:12, Pratibha Rana wrote:
| I am at my wits end trying to create  a dataframe from a list of values that I
| have. here's the code
| 
| try{
|        int size =  argTypes.getColumnCount();
|        std::vector<std::string> nameVec(size);
|        std::vector<int> lenVec(size);
|        std::vector<int> scaleVec(size);

Good. Three STL vectors which should get autmatic conversion via wrap().

[...]

|        //create the dataframe
|        Rcpp::List df = Rcpp::List::create(Rcpp::Named("datatype",nameVec),
|                                           Rcpp::Named("length",lenVec),
|                                           Rcpp::Named("scale",scaleVec));
|        Rcpp::DataFrame df_final = Rcpp::DataFrame::create(df);
|        return df_final;

[...]

| The std::vectors are created fine but the list is not created
| (gdb) p R_PV(df)
| $3 = 0
| 
| 
| I have tried a lot of variation like creating the dataframe directly without
| first creating the list. Nothing seems to be working.

It should work. I believe we posted example on the list, blog, possibly in
RcppExamples, ...


In fact, the latter one may be the best key.  Consider this example taken
straight from the RcppExamples packages (which never became "the" collection
of examples [ contributions welcome ] but has this ...)

RcppExport SEXP RcppDataFrame(SEXP Dsexp) {

    try {					// or use BEGIN_RCPP macro

      // construct the data.frame object
      Rcpp::DataFrame DF = Rcpp::DataFrame(Dsexp);

      // and access each column by name
      Rcpp::IntegerVector a = DF["a"];
      Rcpp::CharacterVector b = DF["b"];
      Rcpp::DateVector c = DF["c"];
      
      // do something
      a[2] = 42;
      b[1] = "foo";
      c[0] = c[0] + 7;                      // move up a week

      // create a new data frame
      Rcpp::DataFrame NDF = 
	  Rcpp::DataFrame::create(Rcpp::Named("a")=a,
				  Rcpp::Named("b")=b,
				  Rcpp::Named("c")=c);

      // and return old and new in list
      return(Rcpp::List::create(Rcpp::Named("origDataFrame")=DF,
				Rcpp::Named("newDataFrame")=NDF));

    } catch( std::exception &ex ) {		// or use END_RCPP macro
	forward_exception_to_r( ex );
    } catch(...) { 
	::Rf_error( "c++ exception (unknown reason)" ); 
    }
    return R_NilValue; // -Wall
}


The main difference is that we use Rcpp vectors.  So you could try 

 -- wrap() in the create() call
 -- converting the Rcpp vectors to STL vectors
 -- debugging why STL vectors don't pass through

Please keep the list posted on your progress.

Dirk

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com  


More information about the Rcpp-devel mailing list