Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to convert DataFrame to Matrix in RCpp

Tags:

r

rcpp

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.

like image 963
uday Avatar asked Jun 22 '14 14:06

uday


People also ask

How do you convert a Dataframe to a matrix?

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.

Can we convert Dataframe to Matrix in R?

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.


1 Answers

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;
}
like image 121
Romain Francois Avatar answered Nov 08 '22 04:11

Romain Francois