[R] Sklyar's inline package: how to return a list?

Feng, Ken ken.feng at citi.com
Fri Oct 5 03:48:44 CEST 2007


Hi,

Below I have a mickey-mouse example using Oleg Sklyar's wonderful inline package.  

The question I have is, how do I return multiple values, say in a list?
Inside the C code, I've also calculated 'sum'.  How do I return this along with 'res'?

Ultimately, I want to return multiple matrix results.  Thanks in advance for any code snipplets/advice!

Regards,
Ken

# --------------------------------------------------------------------------------------------------------------------------

> my.mat
     [,1] [,2] [,3]
[1,]  1.5  4.5  7.5
[2,]  2.5  5.5  8.5
[3,]  3.5  6.5  9.5
> funx( a=my.mat )
     [,1] [,2] [,3]
[1,] -1.5 -4.5 -7.5
[2,] -2.5 -5.5 -8.5
[3,] -3.5 -6.5 -9.5
> 

# --------------------------------------------------------------------------------------------------------------------------
library( inline )

c.code <- "
  SEXP res;
  int     nprotect = 0, nx, ny, x, y;
  double *dptr, *resptr, sum;
  PROTECT(res = Rf_duplicate(a)); nprotect++;
  nx = INTEGER(GET_DIM(a))[0];
  ny = INTEGER(GET_DIM(a))[1];
  dptr   = REAL(a);
  resptr = REAL( res );
  sum = 0.0;
  for (x = 0; x < nx; x++)
    for (y = 0; y < ny; y++)
    {
      resptr[ x + y*nx ] = -dptr[ x + y*nx ];
      sum += -dptr[ x + y*nx ];
    }
  UNPROTECT(nprotect);
  return res;
"
funx <- cfunction(signature(a="array"), c.code)
# test run
my.mat <- matrix( 0.5 + 1:9, nrow=3, ncol=3 )
funx( a=my.mat)



More information about the R-help mailing list