【问题标题】:R: how to extract a row from sparseMatrix as sparseVectorR:如何从 sparseMatrix 中提取一行作为 sparseVector
【发布时间】:2015-10-29 14:31:27
【问题描述】:

我需要将 sparseMatrix 的行提取为 sparseVector,但是 'drop=FALSE' 选项对我不起作用。

为了解释这个问题,我将使用来自extract sparse rows from sparse matrix in r 的示例(我的问题不同,因为我需要将提取的行转换为向量):

i <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7)
A <- sparseMatrix(i, j, x = x)
b <- sparseVector(7,2,10)

现在A[1,,drop=FALSE]b 应该具有相同的值。

但是,A[1,,drop=FALSE] 仍然是一个二维矩阵。所以如果我尝试Matrix::crossprod(b),我会得到:

1 x 1 Matrix of class "dsyMatrix"
     [,1]
[1,]   49

但如果我尝试Matrix::crossprod(A[1,,drop=FALSE]),我会得到:

10 x 10 sparse Matrix of class "dsCMatrix"

[1,] .  . . . . . . . . .
[2,] . 49 . . . . . . . .
[3,] .  . . . . . . . . .
[4,] .  . . . . . . . . .
[5,] .  . . . . . . . . .
[6,] .  . . . . . . . . .
[7,] .  . . . . . . . . .
[8,] .  . . . . . . . . .
[9,] .  . . . . . . . . .
[10,] .  . . . . . . . . .

我怎样才能在第二种情况下以有效的方式获得 49(据我从函数描述中了解到,Matrix::crossprod 应该比 %*% 快)?

另外,b%*%b 工作完全正确,而A[1,,drop=FALSE]%*%A[1,,drop=FALSE] 返回以下错误:

Cholmod error 'A and B inner dimensions must match' at file ../MatrixOps/cholmod_ssmult.c, line 82

【问题讨论】:

    标签: r matrix bigdata sparse-matrix


    【解决方案1】:

    我不太确定是否有一种方法可以(直接)将稀疏矩阵行转换为稀疏向量。

    您收到错误的原因

    A[1,,drop=FALSE]%*%A[1,,drop=FALSE]
    

    是您将具有相同维度的矩阵相乘。你需要转置第二个矩阵:

    A[1,,drop=FALSE] %*% t(A[1,,drop=FALSE])
    

    将返回一个 1x1 稀疏矩阵,然后您可以将其转换为 as.numeric()

    【讨论】:

      猜你喜欢
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 2012-01-17
      • 2014-07-03
      • 1970-01-01
      相关资源
      最近更新 更多