Best way to convert DataFrame to Matrix in RCpp

I have RCpp code, where in part of the code I am trying to convert a DataFrame to a matrix. DataFrame has only numbers (no rows 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 an alternative way (i.e. as.matrix equivalent in R) in RCpp to do the same, something similar to the following code (which DOES NOT work):

 //[[Rcpp::export]] NumericMatrix testDFtoNM(DataFrame x) { NumericMatrix y(x); return y; } 

* EDIT *

Thanks for answers. As Dirk suggested, C ++ code is about 24 times faster than either of the two answers, and the Function version is 2% faster than the internal::convert_using_rfunction .

I initially searched for an answer in RCpp without calling R. It should have made this clear when I posted my question.

+7
r rcpp
source share
2 answers

Similar to the Gabor version, you can do something like this:

 #include <Rcpp.h> using namespace Rcpp ; //[[Rcpp::export]] NumericMatrix testDFtoNM(DataFrame x) { NumericMatrix y = internal::convert_using_rfunction(x, "as.matrix"); return y; } 
+6
source share

If you don't mind calling R back, you can do this like this:

 #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericMatrix DF2mat(DataFrame x) { Function asMatrix("as.matrix"); return asMatrix(x); } 

UPDATE . Comment by Romain Corporation.

+6
source share

All Articles