[R] how to pass matrices from C to R effectively

Hao Cen hcen at andrew.cmu.edu
Fri Nov 13 00:45:17 CET 2009


Hi,

I have C code to produce a lot of matrices to be analyzed. As these
matrices are large (> 1000*10000) and are a lot (> 1000), I am thinking
about how to pass them from C to R effectively.

Would you think about the following solution? In R, I create a wrapper
function

passDataFromCToR = function(row, col) {
         mat = matrix(0, row, col)
	.C("passDataFromCToR",mat)[[1]]
}

It wraps the following C function
void passDataFromCToR (double *m, int *row, int* col){
   mymat = f() // my c function to produce a matrix
   // then I copy mymat to m element by element via a loop

}

Then to use these functions, I would write in R
mat = passDataFromCToR(1000, 10000)

Two issues with this approach are that 1) I have to copy the data once and
2)to the worse, in R I have to know the dimension of the matrices to be
passed from C. This information is not always available.

I would appreciate if you share with me your thoughts on how to solve this
problem better.

thanks

Jeff




More information about the R-help mailing list