Re: [R] search in matrix

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Fri 30 Dec 2005 - 03:35:39 EST

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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Fri Dec 30 03:47:36 2005

This archive was generated by hypermail 2.1.8 : Fri 30 Dec 2005 - 04:40:46 EST