Amin Kaveh
Amin Kaveh

Reputation: 137

How to find the index of the min/max value in a sparse matrix in R?

I have a matrix like this:

> A
9 x 9 sparse Matrix of class "dgCMatrix"
     1    2    3    4    5    6    7    8    9
1 .    0.48 0.10 0.04 .    .    .    .    .   
2 0.48 .    0.10 0.66 0.88 .    .    .    .   
3 0.10 0.10 .    0.59 0.38 .    .    .    .   
4 0.04 0.66 0.59 .    0.46 0.62 .    .    .   
5 .    0.88 0.38 0.46 .    .    .    .    .   
6 .    .    .    0.62 .    .    0.78 0.78 0.16
7 .    .    .    .    .    0.78 .    0.89 0.20
8 .    .    .    .    .    0.78 0.89 .    0.77
9 .    .    .    .    .    0.16 0.20 0.77 .   

I would like to find the index of the min and max values in A without converting A to a normal (not-sparse) matrix. Is there any basic solution for this?

The output of dput(A) is:

new("dgCMatrix", i = c(1L, 2L, 3L, 0L, 2L, 3L, 4L, 0L, 1L, 3L, 
4L, 0L, 1L, 2L, 4L, 5L, 1L, 2L, 3L, 3L, 6L, 7L, 8L, 5L, 7L, 8L, 
5L, 6L, 8L, 5L, 6L, 7L), p = c(0L, 3L, 7L, 11L, 16L, 19L, 23L, 
26L, 29L, 32L), Dim = c(9L, 9L), Dimnames = list(c("1", "2", 
"3", "4", "5", "6", "7", "8", "9"), c("1", "2", "3", "4", "5", 
"6", "7", "8", "9")), x = c(0.48, 0.1, 0.04, 0.48, 0.1, 0.66, 
0.88, 0.1, 0.1, 0.59, 0.38, 0.04, 0.66, 0.59, 0.46, 0.62, 0.88, 
0.38, 0.46, 0.62, 0.78, 0.78, 0.16, 0.78, 0.89, 0.2, 0.78, 0.89, 
0.77, 0.16, 0.2, 0.77), factors = list())

Upvotes: 1

Views: 639

Answers (1)

CJR
CJR

Reputation: 3985

I'm just gonna set up an example:

require(Matrix)

A <- matrix(1:100, nrow=10) %% 15
A[A < 7] <- 0
A <- Matrix(A, sparse=T)

Yep, this is a sparse matrix:

> A
10 x 10 sparse Matrix of class "dgCMatrix"
                                   
 [1,]  . 11  .  . 11  .  . 11  .  .
 [2,]  . 12  7  . 12  7  . 12  7  .
 [3,]  . 13  8  . 13  8  . 13  8  .
 [4,]  . 14  9  . 14  9  . 14  9  .
 [5,]  .  . 10  .  . 10  .  . 10  .
 [6,]  .  . 11  .  . 11  .  . 11  .
 [7,]  7  . 12  7  . 12  7  . 12  7
 [8,]  8  . 13  8  . 13  8  . 13  8
 [9,]  9  . 14  9  . 14  9  . 14  9
[10,] 10  .  . 10  .  . 10  .  . 10

Logical tests on it work just fine

> A == max(A)
10 x 10 sparse Matrix of class "lgCMatrix"
                         
 [1,] . : . . : . . : . .
 [2,] . : : . : : . : : .
 [3,] . : : . : : . : : .
 [4,] . | : . | : . | : .
 [5,] . . : . . : . . : .
 [6,] . . : . . : . . : .
 [7,] : . : : . : : . : :
 [8,] : . : : . : : . : :
 [9,] : . | : . | : . | :
[10,] : . . : . . : . . :

And we can get row & column indices of max(A) no problem:

> which(A == max(A), arr.ind=T)
     row col
[1,]   4   2
[2,]   9   3
[3,]   4   5
[4,]   9   6
[5,]   4   8
[6,]   9   9

I would suggest that you figure out which of these steps isn't giving you the output it should.

Upvotes: 3

Related Questions