[R] index of min elements in matrix

Marc Schwartz marc_schwartz at me.com
Thu Sep 10 20:42:52 CEST 2009


On Sep 10, 2009, at 1:34 PM, annie Zhang wrote:

> Hi, All,
>
> How can I get the indices of the minimum elements in a matrix  
> without using
> a loop?
>
> For example, if the matrix is
>
> 4 5 2
> 2 8 9
> 5 2 3
>
> Then I want to output (1,3), (2,1), (3,2).
>
> Thanks,
>
> Annie


mat <- matrix(c(4, 2, 5, 5, 8, 2, 2, 9, 3), 3)

 > mat
      [,1] [,2] [,3]
[1,]    4    5    2
[2,]    2    8    9
[3,]    5    2    3


 > which(mat == min(mat), arr.ind = TRUE)
      row col
[1,]   2   1
[2,]   3   2
[3,]   1   3


See ?which and take note of the arr.ind argument.

HTH,

Marc Schwartz




More information about the R-help mailing list