[R] Passing an R matrix to a C program

Martin Maechler maechler at stat.math.ethz.ch
Thu Sep 27 15:26:37 CEST 2001


>>>>> "AgusL" == Agustin Lobo <alobo at ija.csic.es> writes:

    AgusL> Hello,

    AgusL> I'm starting to write a C function that gets
    AgusL> a list and a matrix from R. I'm using .Call
    AgusL> because I've undertood that this is recommended
    AgusL> to handle lists (am I wrong?).  My problem is that I
    AgusL> can pass the matrix as a vector, but not as a 2D array.

Yes, they are vectors in one sense, the main reason being that C does not
have really have 2D arrays [another reason being that Fortran has this
equivalence by definition].
The example you give is just a typical implementation of matrices in C,
but AFAIK not at all the most common one for numerical computation.

The R functions row() and col()  call the following C function 
(from src/main/array.c) which should you how to deal with arrays:

---------------------------------------------------------------
  SEXP do_rowscols(SEXP call, SEXP op, SEXP args, SEXP rho)
  {
      SEXP ans;
      int i, j, nr, nc;

      if (length(args) != 1)
	  error("incorrect number of args to row/col");
      if (!isMatrix(CAR(args)))
	  error("a matrix is required as arg to row/col");

      nr = nrows(CAR(args));
      nc = ncols(CAR(args));

      ans = allocMatrix(INTSXP, nr, nc);

      switch (PRIMVAL(op)) {
      case 1:
	  for (i = 0; i < nr; i++)
	      for (j = 0; j < nc; j++)
		  INTEGER(ans)[i + j * nr] = i + 1;
	  break;
      case 2:
	  for (i = 0; i < nr; i++)
	      for (j = 0; j < nc; j++)
		  INTEGER(ans)[i + j * nr] = j + 1;
	  break;
      }
      return ans;
  }
---------------------------------------------------------------

For that case (and in others), people may like to use C macros, e.g.,

#define ANS(I_,J_)  INTEGER(ans)[I_ + J_ * nr] 

would allow you to have

       ANS(i,j) = i + 1;
...
       ANS(i,j) = j + 1;

in the above function.
But note that this macros relies on `nr' being defined and having the
correct value.  One reason we tend not to use them.

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO D10	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list