[Rcpp-devel] binding, combining vectors

Dirk Eddelbuettel edd at debian.org
Thu Dec 13 17:29:43 CET 2012


On 13 December 2012 at 10:01, Romain Francois wrote:
| Hello,
| 
| I'd like to add a functionality to "bind" vectors of the same type (well 
| sugar expressions really, but let's say it is vectors for the sake of 
| this email).
| 
| So essentially I'd like something similar to what "c" does in R :
| 
|  > c( letters, letters )
|   [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" 
| "q" "r" "s"
| [20] "t" "u" "v" "w" "x" "y" "z" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" 
| "k" "l"
| [39] "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"
| 
| 
| I don't want to call it "c", and I'd like suggestions : combine, bind ?
| 
| The idea is to avoid writing code like this:
| 
| CharacterVector x, y ;
| CharacterVector z( x.size() + y.size() ) ;
| int i=0;
| for( ; i<x.size(); i++) z[i] = x[i] ;
| for( int j=0; j<y.size(); i++, j++) z[i] = y[j] ;
| 
| I know it is not a big deal for people to write this code, but for 
| example this does not handle the names of the elements, ... and 
| internally I can use more efficient code

The STL more or less has that already, just combine two calls to copy():

-----------------------------------------------------------------------------
#include <Rcpp.h>

// [[Rcpp::export]] 
std::vector<std::string> concat(std::vector<std::string> x,
std::vector<std::string> y) {

  std::vector<std::string> z(x.size() + y.size());

  std::copy(x.begin(), x.end(), z.begin());
  std::copy(y.begin(), y.end(), z.begin() + x.size());

  return(z);
}


/*** R
concat(letters[1:5], letters[1:4])
***/
-----------------------------------------------------------------------------


R> sourceCpp("/tmp/concat.cpp")

R> concat(letters[1:5], letters[1:4])
[1] "a" "b" "c" "d" "e" "a" "b" "c" "d"
R> 


Dirk

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


More information about the Rcpp-devel mailing list