[Rcpp-devel] Dispatch on sparse and dense matrices...

Søren Højsgaard sorenh at math.aau.dk
Sun Dec 8 22:47:38 CET 2013


Dear all,

I want to do some computation on a matrix, irrespective of whether it is a numeric matrix, an integer matrix or a sparse matrix (a dgCMatrix which can be handled with RcppEigen). For simplicity, I want to compute the sum of the elements. 

To do so I use a template 

template <typename TT>
SEXP do_compute( SEXP XX_ ){
  const TT X(as<TT>(XX_));
  return wrap(X.sum()); // some computation on X...
};

I then dispatch depending on input type with

// [[Rcpp::export]]
SEXP compute ( SEXP XX_ ){
  int type = TYPEOF(XX_) ;
  Rf_PrintValue(wrap(type));
  switch( type ){
  case 13 : return do_compute<MapMati>(XX_); // matrix - integer 
  case 14 : return do_compute<MapMatd>(XX_); // matrix - double
  case 25 : return do_compute<MSpMat>(XX_); // dgCMatrix
  }
  return R_NilValue ;
}

and the numbers 13, 14, 25 are disclosed to by simply printing the type. I know that for integers and doubles I can do something "nicer":

// [[Rcpp::export]]
SEXP compute2 ( SEXP XX_ ){
  int type = TYPEOF(XX_) ;
  Rf_PrintValue(wrap(type));
  switch( type ){
  case INTSXP : return do_compute<MapMati>(XX_); // matrix - integer 
  case REALSXP : return do_compute<MapMatd>(XX_); // matrix - double
  case 25 : return do_compute<MSpMat>(XX_); // dgCMatrix
  }
  return R_NilValue ;
}

Questions:

Is there a similar keyword for sparse matrices?? 

If not, is the "code" 25 safe to use in an R-package??

Are there more elegant ways of handling the dispatch ??

The source file is attached. Thanks in advance.

Søren


-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: dispatch.cpp
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20131208/6845e470/attachment.ksh>


More information about the Rcpp-devel mailing list