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

北战南征 提交于 2019-12-08 09:12:19

问题


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?


回答1:


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)))
}


来源:https://stackoverflow.com/questions/32499520/r-rbind-from-matrix-package-does-not-work-for-sparse-matrices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!