[Rcpp-devel] Rcpp version of c( )

Dirk Eddelbuettel edd at debian.org
Thu Jan 23 02:16:42 CET 2014


On 21 January 2014 at 22:02, Søren Højsgaard wrote:
| I have made the following primitive "concatenate" function, because I couldn't find one in Rcpp:
| 
| template <const int RTYPE>
| Vector<RTYPE> do_conc_(Vector<RTYPE> x, Vector<RTYPE> y){
|   int nx=x.size(), n=x.size()+y.size(),i,j;
|   Vector<RTYPE> out=no_init(n);
|   for (i=0; i<nx; ++i){ out[ i ] = x[ i ];}
|   for (j=i, i=0; j<n; ++j, ++i){ out[ j ] = y[i] ;}
|   return out;
| }
| 
| // [[Rcpp::export]]
| SEXP conc( SEXP& XX_, SEXP& YY_){
|   int type = TYPEOF(XX_) ;
|   switch( type ){
|   case INTSXP  : return do_conc_<INTSXP> ( XX_, YY_ ) ;
|   case REALSXP : return do_conc_<REALSXP>( XX_, YY_ ) ;
|   case STRSXP  : return do_conc_<STRSXP> ( XX_, YY_ ) ;
|   case VECSXP  : return do_conc_<VECSXP> ( XX_, YY_ ) ;
|   }
|   return R_NilValue ;
| }
| 
| As you can see it assumes that the two inputs XX_ and YY_ are of the same type, and it fails to copy names to the output. If I have missed any such functionality in Rcpp then I would be happy to know...

My instinct would be to use RcppArmadillo vectors:

R> cppFunction("arma::colvec conc(const arma::colvec & x, const arma::colvec & y) { return arma::join_cols(x, y); }", depends="RcppArmadillo")
R> conc(1:3, 11:13)
     [,1]
[1,]    1
[2,]    2
[3,]    3
[4,]   11
[5,]   12
[6,]   13
R> 

For more _generic_ solutions, the STL offers a lot.  

Dirk

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com


More information about the Rcpp-devel mailing list