【发布时间】:2016-05-20 16:19:42
【问题描述】:
R中的cbind在重复调用中相对比较耗时,但它对各种数据类型也很强大。
绑定两个矩阵时,我编写的代码比 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))
【问题讨论】: