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) )