I have an RCpp code, where in a part of code I am trying to convert a DataFrame to a Matrix. The DataFrame only has numbers (no strings or dates).
The following code works:
//[[Rcpp::export]]
NumericMatrix testDFtoNM1(DataFrame x) {
int nRows=x.nrows();
NumericMatrix y(nRows,x.size());
for (int i=0; i<x.size();i++) {
y(_,i)=NumericVector(x[i]);
}
return y;
}
I was wondering if there is alternative way (i.e. equivalent of as.matrix
in R) in RCpp to do the same, something similar to the following code below (which does NOT work):
//[[Rcpp::export]]
NumericMatrix testDFtoNM(DataFrame x) {
NumericMatrix y(x);
return y;
}
* EDIT *
Thanks for the answers. As Dirk suggested, the C++ code is around 24x faster than either of the two answers and Function
version is 2% faster than the internal::convert_using_rfunction
version.
I was originally looking for an answer within RCpp without calling R. Should have made that clear when I posted my question.