Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a matrix in R and pass it to C++

Tags:

c++

r

rcpp

I have a matrix defined in R. I need to pass this matrix to a c++ function and do operations in C++. Example: In R, define a matrix,

A <- matrix(c(9,3,1,6),2,2,byrow=T)
PROTECT( A = AS_NUMERIC(A) );
double* p_A = NUMERIC_POINTER(A);

I need to pass this matrix to a C++ function where variable 'data' of type vector<vector<double>> will be initialized with the matrix A.

I couldn't seem to figure out how to do this. I am thinking in more complicated way then I should be, I bet there is an easy way to do this.

like image 839
intsymmetry Avatar asked Nov 10 '12 18:11

intsymmetry


2 Answers

As Paul said, I would recommend using Rcpp for that kind of things. But it also depends what you want your vector< vector<double> > to mean. Assuming you want to store columns, you might process your matrix like this:

require(Rcpp)
require(inline)

fx <- cxxfunction( signature( x_ = "matrix" ), '
    NumericMatrix x(x_) ;
    int nr = x.nrow(), nc = x.ncol() ;
    std::vector< std::vector<double> > vec( nc ) ;
    for( int i=0; i<nc; i++){
        NumericMatrix::Column col = x(_,i) ;
        vec[i].assign( col.begin() , col.end() ) ;
    }
    // now do whatever with it
    // for show here is how Rcpp::wrap can wrap vector<vector<> >
    // back to R as a list of numeric vectors
    return wrap( vec ) ;
', plugin = "Rcpp" )
fx( A )
# [[1]]
# [1] 9 1
# 
# [[2]]
# [1] 3 6    
like image 128
Romain Francois Avatar answered Sep 27 '22 23:09

Romain Francois


You probably want to use Rcpp. This package allows easy integration of R and C++, including passing objects from R to C++. The package is available on CRAN. In addition, a number of packages on CRAN use Rcpp, so they could serve as inspiration. The website of Rcpp is here:

http://dirk.eddelbuettel.com/code/rcpp.html

which includes a few tutorials.

like image 26
Paul Hiemstra Avatar answered Sep 28 '22 01:09

Paul Hiemstra