[Rcpp-devel] Rcpp version of c( )

Romain François romain at r-enthusiasts.com
Wed Jan 22 01:22:50 CET 2014


Hi, 

There is currently nothing like that. It is quite hard to generalize. 

You might like std::merge, e.g. 

template <typename Vec>
Vec do_conc_(Vec x, Vec y){
  Vec out=no_init(x.size()+y.size());
  std::merge( x.begin(), x.end(), y.begin(), y.end(), out.begin() ) ;
  return out;
}

We could want to generalize this to arbitrary sugar expressions, so that we could do e.g. 

conc( x+x, y+y ) ;

without having to materialize x+x and y+y into their own memory ...

Perhaps it would look like this: 

template <int RTYPE, typename T1, typename T2>
Vector<RTYPE> concat( const T1& t1, const T2& t2 ){
   // use static_assert to make sure T1 and T2 are sugar expressions

   int n = t1.size() + t2.size() ;
   Vector<RTYPE> out = no_init(n) ;

   std::merge( t1.begin(), t1.end(), t2.begin(), t2.end(), out.begin() ) ;

   return out ;
}

Then as Kevin hints (and has opened an issue in https://github.com/romainfrancois/Rcpp11/issues/92) we can want to go further and want something with multiple inputs.

Interesting idea, I guess lots of work to generalize it. 

Romain


Le 21 janv. 2014 à 23:02, Søren Højsgaard <sorenh at math.aau.dk> a écrit :

> Dear all,
> 
> 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...
> 
> Cheers
> Søren



More information about the Rcpp-devel mailing list