This script, cbind with a bunch of vectors, is perfectly tuned to dump information directly into a sparse, column-oriented matrix ( dgCMatrix class).
There will be a function that will do this:
sv.cbind <- function (...) { input <- lapply( list(...), as, "dsparseVector" ) thelength <- unique(sapply(input,length)) stopifnot( length(thelength)==1 ) return( sparseMatrix( x=unlist(lapply(input,slot,"x")), i=unlist(lapply(input,slot,"i")), p=c(0,cumsum(sapply(input,function(x){length( x@x )}))), dims=c(thelength,length(input)) ) ) }
From a quick test, this looks about 10 times faster than forcing + cbind :
require(microbenchmark) xx <- lapply( 1:10, function (k) { sparseVector( x=rep(1,100), i=sample.int(1e4,100), length=1e4 ) } ) microbenchmark( do.call( sv.cbind, xx ), do.call( cBind, lapply(xx,as,"sparseMatrix") ) )
source share