Search code examples
rmatrixsparse-matrixrbindcbind

R: rBind from Matrix package does not work for sparse matrices


I have the following code:

concept_vectors <- foreach(j = 1:2, .combine=rBind, .packages="Matrix") %do% {
   Matrix::colMeans(sparseX[1:10,],sparseResult=TRUE)
}

which results in the following error message:

Error in { : no method for coercing this S4 class to a vector

However, if I either remove 'sparseResult=TRUE' option, or do not use colMeans at all, the code works, even if without colMeans, sparseX is still an S4 object.

If I replace rBind with rbind2 directly, then I still see the following error:

error calling combine function:
<simpleError in .__H__.rbind(deparse.level = 0, x, y): no method for coercing this S4 class to a vector>

Do you know any workaround for this?


Solution

  • The problem was that colMeans returs sparseVector and not sparseMatrix. Therefore, rBind is not able to combine several sparseVector objects into sparseMatrix.

    As mentioned at https://stackoverflow.com/a/8979207/1075993, the solution is to write a function, that will combine multiple sparseVector objects into sparseMatrix:

    sameSizeVectorList2Matrix <- function(vectorList){  
        sm_i<-NULL
        sm_j<-NULL
        sm_x<-NULL
        for (k in 1:length(vectorList)) {
            sm_i <- c(sm_i,rep(k,length(vectorList[[k]]@i)))
            sm_j <- c(sm_j,vectorList[[k]]@i)
            sm_x <- c(sm_x,vectorList[[k]]@x)
        }
    return (sparseMatrix(i=sm_i,j=sm_j,x=sm_x,dims=c(length(vectorList),vectorList[[1]]@length)))
    }