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 leads to the following error message:

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

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

If I replaced 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 about this workaround?

0
source share
1 answer

The problem was that colMeans returns regressive branches, not sparseMatrix. Therefore, rBind cannot combine multiple sparse Vector objects in sparseMatrix.

As mentioned in fooobar.com/questions/1390737 / ... , the solution is to write a function that combines several sparseVector objects in 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))) } 
0
source

Source: https://habr.com/ru/post/1390739/


All Articles