【问题标题】:R: rBind from Matrix package does not work for sparse matricesR:来自 Matrix 包的 rBind 不适用于稀疏矩阵
【发布时间】:2015-09-10 10:35:29
【问题描述】:

我有以下代码:

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

这会导致以下错误消息:

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

但是,如果我删除 'sparseResult=TRUE' 选项,或者根本不使用 colMeans,代码就可以工作,即使没有 colMeans,sparseX 仍然是一个 S4 对象

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

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

您知道任何解决方法吗?

【问题讨论】:

    标签: r matrix sparse-matrix rbind cbind


    【解决方案1】:

    问题在于 colMeans 返回 sparseVector 而不是 sparseMatrix。因此,rBind 无法将多个 sparseVector 对象组合成 sparseMatrix。

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

    【讨论】:

    • 我认为在这样的循环中使用 c() 会给你一个额外的 O(length(vectorList)) 运行时间因素。 stackoverflow.com/a/8979207/1075993 中的解决方案似乎效率更高。
    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多