Search code examples
rmatrixsparse-matrix

Error: "argument to 'which' is not logical" for sparse logical matrix


Here's what I am doing:

  1. Loading sparse matrix from a file.
  2. Extracting indices(col, row) which have the values in this sparse matrix.
  3. Use these indices and the values for further computation.

This works fine when I am executing the steps on R command prompt. But when its done inside a function of a package, step 2 throws the following error:

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

Here's the sample code with an example:

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

The loaded matrices in my case are of type: dsCMatrix, dgCMatrix.

class(matA != 0): lsCMatrix

I don't understand why should this lead to the error.

Please note the following:

  1. Can't share the dumped sparse matrix file. Hence shown an example by creating a dummy matrix for step 1.
  2. The dimensions of the sparse matrix are huge. So converting the sparse matrix to a regular matrix exceeds the memory limit.

Libraries: The package that I am using mentions the following libraries:

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

Solution

  • You need to load the library Matrix, chances are the package does not load it. See example below:

    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
    

    If Matrix is already loaded, it might be the Matrix::which is masked somehow. you can do:

    Matrix::which(mat>0)