constructing a Data Frame in Rcpp

前端 未结 4 1729
名媛妹妹
名媛妹妹 2020-12-14 23:20

I want to construct a data frame in an Rcpp function, but when I get it, it doesn\'t really look like a data frame. I\'ve tried pushing vectors etc. but it leads to the same

4条回答
  •  [愿得一人]
    2020-12-15 00:01

    Using the information from @baptiste's answer, this is what finally does give a well formed data frame:

    RcppExport SEXP makeDataFrame(SEXP in) {
        Rcpp::DataFrame dfin(in);
        Rcpp::DataFrame dfout;
        Rcpp::CharacterVector namevec;
        std::string namestem = "Column Heading ";
        for (int i=0;i<2;i++) {
            dfout.push_back(dfin(i));
            namevec.push_back(namestem+std::string(1,(char)(((int)'a') + i)));
        }
        dfout.attr("names") = namevec;
        Rcpp::DataFrame x;
        Rcpp::Language call("as.data.frame",dfout);
        x = call.eval();
        return x;
    }
    

    I think the point remains that this might be inefficient due to push_back (as suggested by @Dirk) and the second Language call evaluation. I looked up the rcpp unitTests, and haven't been able to come up with something better yet. Anybody have any ideas?

    Update:

    Using @Dirk's suggestions (thanks!), this seems to be a simpler, efficient solution:

    RcppExport SEXP makeDataFrame(SEXP in) {
        Rcpp::DataFrame dfin(in);
        Rcpp::List myList(dfin.length());
        Rcpp::CharacterVector namevec;
        std::string namestem = "Column Heading ";
        for (int i=0;i

提交回复
热议问题