R function implementation in C ++ Rcpp

I have the following R code:

CutMatrix <- FullMatrix[, colSums( FullMatrix[-1,] != FullMatrix[-nrow( FullMatrix ), ] ) > 0]

What takes the matrix is ​​FullMatrix and makes CutMatrix, finding which columns in FullMatrix have columns with more than 1 unique value, so all columns with the same value are excluded. I am wondering if I can use Rcpp to speed this up for large matrices, but I'm not sure if this is the best way to do this - is there an easy way to do this with sugar (say by going through the columns and counting the number of unique values) , or if I have to use something more complicated from STL.

I thought that maybe something like the following - this is the beginning (I could not completely get through) - an attempt to perform the operation between the colSums brackets in the R function, but I do not think that I am setting the matrix correctly, as it does not work .

src <- '
//Convert the inputted character matrix of DNA sequences an Rcpp class.
Rcpp::CharacterMatrix mymatrix(inmatrix);

//Get the number of columns and rows in the matrix
int ncolumns = mymatrix.ncol();
int numrows = mymatrix.nrow();

//Get the dimension names
Rcpp::List dimnames = mymatrix.attr("dimnames");

Rcpp::CharacterMatrix vec1 = mymatrix(Range(1,numrows),_);
Rcpp::CharacterMatrix vec2 = mymatrix(Range(0,numrows-1),_); 
'

uniqueMatrix <- cxxfunction(signature(inmatrix="character"), src, plugin="Rcpp")

Thanks Ben.

+4
source share
1 answer

It returns LogicalVector, that is FALSEfor all of these columns to one value uniquethat you can use for a subset of your the R matrix.

require( Rcpp )
cppFunction('
  LogicalVector unq_mat( CharacterMatrix x ){

  int nc = x.ncol() ;
  LogicalVector out(nc);

  for( int i=0; i < nc; i++ ) {
    out[i] = unique( x(_,i) ).size() != 1 ;
    }
  return out;
}'
)

You can use it like this:

#  Generate toy data
set.seed(1)
mat <- matrix( as.character(c(rep(1,5),sample(3,15,repl=TRUE),rep(5,5))),5)
     [,1] [,2] [,3] [,4] [,5]
[1,] "1"  "1"  "3"  "1"  "5" 
[2,] "1"  "2"  "3"  "1"  "5" 
[3,] "1"  "2"  "2"  "3"  "5" 
[4,] "1"  "3"  "2"  "2"  "5" 
[5,] "1"  "1"  "1"  "3"  "5"

mat[ , unq_mat(mat) ]
     [,1] [,2] [,3]
[1,] "1"  "3"  "1" 
[2,] "2"  "3"  "1" 
[3,] "2"  "2"  "3" 
[4,] "3"  "2"  "2" 
[5,] "1"  "1"  "3" 

Some basic benchmarking ...

applyR <- function(y) { y[ , apply( y , 2 , function(x) length( unique(x) ) != 1L ) ] }
rcpp <- function(x) x[ , unq_mat(x) ]

require(microbenchmark)
microbenchmark( applyR(mat) , rcpp(mat) )
#Unit: microseconds
#        expr    min      lq median     uq    max neval
# applyR(mat) 131.94 134.737 136.31 139.29 268.07   100
#   rcpp(mat)   4.20   4.901   7.70   8.05  13.30   100
+2
source

All Articles