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.
Convert a Data Frame into a Numeric Matrix in R Programming – data. matrix() Function. data. matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.
Convert Data Frame to Matrix in R where frame is the dataframe and rownames. force is logical indicating if the resulting matrix should have character (rather than NULL ) rownames . The default, NA , uses NULL rownames if the data frame has 'automatic' row. names or for a zero-row data frame.
Similar to Gabor's 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With