Skip to content

search in matrix

2 messages · Florent Bresson, Marc Schwartz (via MN)

#
I'm dealing with a matrix like :

     "x"  "y"  "z"
[1,]  2    4     1
[2,]  6    1     2
...
[n,]  7    3     1

For each row I would like to know the header of the
column which corresponds to the minimum value. In the
case of my matrix, I would like to obtain the
following vector :

z y ... z

Any idea ?
#
On Thu, 2005-12-29 at 17:20 +0100, Florent Bresson wrote:
x y z
[1,] 2 4 1
[2,] 6 1 2
[3,] 7 3 1
[1] "z" "y" "z"


apply() (using '1') passes each row to the function which.min() which
returns the index of the minimum value for the row. The indices are then
passed to colnames(mat), returning the column names on a row by row
basis as a vector.

See ?colnames, ?apply and ?which.min for more information.

HTH,

Marc Schwartz