Skip to content
Prev 4930 / 10988 Next

[Rcpp-devel] Joining each row of CharacterMatrix to return a CharacterVector?

Hello,

We don't know your function f, so this is hard to say. Anyway, this 
below implements something similar to apply(.,1,paste0) in rcpp (current 
devl version):

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
CharacterVector pasteColumns(CharacterMatrix m){
     String buffer ;
     int nc = m.ncol(), nr = m.nrow() ;
     CharacterVector out(nr) ;
     for( int i=0; i<nr; i++){
         CharacterMatrix::Row row = m(i,_) ;
         buffer = "" ;
         for( int j=0; j<nc; j++){
             buffer += row[j] ;
         }
         out[i] = buffer ;
     }
     return out ;
}

With this, I get these timings:

     nc <- 100; nr <- 2e4
     M <- matrix( sample(letters, nc*nr, replace = TRUE) , ncol = nc )

     require(microbenchmark)
     microbenchmark(
         pasteColumns(M),
         apply(M, 1, paste0)
         )
     Unit: milliseconds
                  expr       min        lq    median        uq      max
     1 apply(M, 1, paste0) 451.39975 484.41435 495.92757 501.58728 714.1418
     2     pasteColumns(M)  67.91322  68.29269  70.34704  77.09383 145.9161



Le 10/12/12 23:43, hickey at wehi.EDU.AU a ?crit :