search in matrix

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

search in matrix

Bugzilla from f_bresson@yahoo.fr
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 ?

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Reply | Threaded
Open this post in threaded view
|

Re: search in matrix

Marc Schwartz (via MN)
On Thu, 2005-12-29 at 17:20 +0100, Florent Bresson wrote:

> 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 ?


> mat
     x y z
[1,] 2 4 1
[2,] 6 1 2
[3,] 7 3 1


> colnames(mat)[apply(mat, 1, which.min)]
[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

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html