R fast cbind mat, rix usando Rcpp
cbind
en R es relativamente lento en llamadas repetidas, pero también es poderoso para varios tipos de datos. He escrito código que es 3 veces más rápido quecbind
cuando se unen dos matrices. Perobind_cols
endplyr
el paquete es simplemente 100 veces más rápido quecbind
. Es una pena que no pueda tomar la matriz como entrada. ¿Alguien puede hacer que el siguiente código sea más rápido? Además, ¿cómo puedo unir rápidamente una matriz dispersa? Aquí está el código que usé:
require( Rcpp )
func <- 'NumericMatrix mmult(NumericMatrix a,NumericMatrix b) {
//the colnumber of first matrix
int acoln=a.ncol();
//the colnumber of second matrix
int bcoln=b.ncol();
//build a new matrix, the dim is a.nrow() and acoln+bcoln
NumericMatrix out(a.nrow(),acoln+bcoln) ;
for (int j = 0; j < acoln + bcoln; j++) {
if (j < acoln) {
out(_,j) = a(_,j);
} else {
//put the context in the second matrix to the new matrix
out(_,j) = b(_,j-acoln);
}
}
return out ;
}'
a <- matrix(rep(1,2000*100),2000)
b <- matrix(rep(2,2000*10),2000)
cppFunction(func)
system.time(for (i in seq(1,800)) {mmult(a,b)})
system.time(for (i in seq(1,800)) {cbind(a,b)})
identical(mmult(a,b),cbind(a,b))