1

Is there any easy syntax to extract a Row of a DataFrame (that contains only numeric) within RCpp either as a part of a DataFrame class or as some other class?

Currently I have been doing the following:

DataFrame myFunc(DataFrame& x) {
  ...

  // Suppose I need to get the 10th row
  int nCols=x.size();
  std::vector<double> y;
  y.reserve(nCols);
  for (int j=0; j<nCols;j++) {
    y.push_back((as<vector<double> >(x[j]))[9]); // index in C++ starts at 0
  }

  ...
}
uday
  • 6,453
  • 13
  • 56
  • 94
  • 2
    Possible duplicate of http://stackoverflow.com/questions/22828361/rcpp-function-to-select-and-to-return-a-sub-dataframe. See also http://stackoverflow.com/questions/10911971/rcpp-recommended-code-structure-when-using-data-frames-with-rcpp-inline – Andrie Jun 24 '14 at 15:39

1 Answers1

6

There no such thing as a data frame row, it only exist virtually. So what you have is pretty close to what you ought to do. However you should use a NumericVector instead of a std::vector<double> which would copy all of the data from the column for almost nothing.

Updated pseudo code:

DataFrame myFunc(DataFrame& x) {
    ...

    // Suppose I need to get the 10th row
    int nCols=x.size();
    NumericVector y(nCols);
    for (int j=0; j<nCols;j++) {
        NumericVector column = x[j] ;
        y[i] = column[9] ;
    }

    ...
}       
Romain Francois
  • 17,432
  • 3
  • 51
  • 77