Этот сценарий, cbind
с кучей векторов, идеально подходит для выгрузки информации прямо в разреженную, ориентированную на столбцы матрицу (dgCMatrix
класс).* Вот функция, которая сделает это:
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))
) )
}
Из быстрого теста это выглядит примерно в 10 раз быстрее, чем принуждение + 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") ) )
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# do.call(sv.cbind, xx) 1.398565 1.464517 1.540172 1.49487 1.55911 3.455421 100 a
# do.call(cBind, lapply(xx, as, "sparseMatrix")) 16.037890 16.356268 16.956326 16.59854 17.49956 20.256253 100 b