【问题标题】:Error: "argument to 'which' is not logical" for sparse logical matrix错误:稀疏逻辑矩阵的“'which' 参数不符合逻辑”
【发布时间】:2020-06-14 13:54:51
【问题描述】:

这是我正在做的事情:

  1. 从文件加载稀疏矩阵。
  2. 提取具有此稀疏矩阵中的值的索引(col, row)。
  3. 使用这些索引和值进行进一步计算。

当我在 R 命令提示符下执行这些步骤时,这可以正常工作。 但是当它在一个包的函数中完成时,第 2 步会抛出以下错误

Error in which(matA != 0, arr.ind = TRUE) :
  argument to 'which' is not logical

这是带有示例的示例代码:

matA <- as(Matrix(c(0,1,2,1,0,0,3,0,2), nrow=3, ncol=3), "sparseMatrix")  # Step 1
nz <- which(matA != 0, arr.ind = TRUE)  # Step 2

> nz
     row col
[1,]   2   1
[2,]   3   1
[3,]   1   2
[4,]   1   3
[5,]   3   3

在我的例子中,加载的矩阵类型为:dsCMatrix、dgCMatrix。

class(matA != 0): lsCMatrix

我不明白为什么这会导致错误。

请注意以下几点:

  1. 无法共享转储的稀疏矩阵文件。因此,通过为步骤 1 创建一个虚拟矩阵来展示一个示例。
  2. 稀疏矩阵的维数很大。所以将稀疏矩阵转换为正则矩阵超出了内存限制。

: 我使用的包提到了以下库:

Suggests: 
    testthat (>= 2.1.0),
    knitr,
    rmarkdown
Imports: 
    irlba,
    text2vec,
    dplyr,
    magrittr,
    Matrix,
    readr,
    rlang,
    data.table,
    stringr,
    here

【问题讨论】:

  • 请注明library来电。
  • @jay.sf 添加了包中提到的库。

标签: r matrix sparse-matrix


【解决方案1】:

您需要加载库Matrix,可能包没有加载它。请参见下面的示例:

library(Seurat)
mat = pbmc_small@assays$RNA@counts
class(mat)
[1] "dgCMatrix"
attr(,"package")
[1] "Matrix"

which(mat>0)
Error in which(mat > 0) : argument to 'which' is not logical

library(Matrix)
head(which(mat>0,arr.ind=TRUE))
         row col
CD79B      2   1
HLA-DQB1   6   1
LTB        9   1
SP100     12   1
CXCR4     23   1
CD3D      31   1

如果 Matrix 已经加载,它可能是 Matrix:: 以某种方式被屏蔽。你可以这样做:

Matrix::which(mat>0)

【讨论】:

  • 函数里面,我添加了print(dim(matA))。并且脚本在执行上述行之前打印以下语句: Loading required package: Matrix 所以我想问题不是你提到的。
  • 好吧,我测试过了,没有理由不工作。您可以尝试使用 Matrix::which(matA > 0) 显式调用 which
  • 你是对的。显式调用 Matrix::which 有效。似乎该脚本正在使用另一个库的 which。非常感谢。
猜你喜欢
  • 2017-06-22
  • 2015-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
相关资源
最近更新 更多