cbind
在R中重复调用时时间相对较长,但对于各种数据类型也很有用。我编写了一段代码,将两个矩阵绑定时比cbind
快3倍。但是,在dplyr
包中的bind_cols
仅比cbind
快100倍。可惜它不能接受矩阵作为输入。请问有人能让下面的代码更快吗?另外,我该如何快速绑定稀疏矩阵?以下是我使用的代码:
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))