R:Matrix包中的rBind不适用于稀疏矩阵 [英] R: rBind from Matrix package does not work for sparse matrices

查看:136
本文介绍了R:Matrix包中的rBind不适用于稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

但是,如果我删除'sparseResult = TRUE'选项,或者根本不使用colMeans,则代码有效,即使没有colMeans,sparseX仍然是S4对象.

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.

如果我直接用rbind2替换rBind,那么我仍然看到以下错误:

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?

推荐答案

问题是colMeans会返回sparseVector而不是sparseMatrix.因此,rBind无法将多个sparseVector对象组合到sparseMatrix中.

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

https://stackoverflow.com/a/8979207/1075993 所述,解决方案是编写一个函数,它将多个sparseVector对象合并为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)))
}

这篇关于R:Matrix包中的rBind不适用于稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆