The apply function takes another function as the argument to be applied to
each row (or column) of the matrix. You can use an existing function like
you did with 'max' and in this case there is an existing function called
'which.max' that does exactly what you want. If there is not an
existing
function then you can write your own and use that, for example if you want
to find which column the median is in (I don't know of an existing
which.median function) we can write our own function:
which.median <- function(x) { which( x==median(x) )[1] }
apply( m, 1, which.median )
We can even combine the 2 steps and use an anonymous function (we create
the function and use it, but never save it to a named variable):
apply( m, 1, function(x) { which(x=median(x))[1] } )
We can write and use more complicated functions as well, but this should
get you started.
On Thu, Jan 10, 2013 at 4:59 PM, ej <ejohnso9@earthlink.net> wrote:
> So, I am just trying to learn R...
>
> Here is a rather contrived example that would be pretty obvious to me in
> terms of writing code to loop through elements, but the slick, fast,
> compact
> way of expressing this in R is not obvious to me.
>
> Here's code to generate a simple matrix of data:
>
> > m <- floor(matrix(runif(24, 1, 100), 8, 3))
> > m
> [,1] [,2] [,3]
> [1,] 75 5 15
> [2,] 82 79 2
> [3,] 72 24 55
> [4,] 88 38 3
> [5,] 42 82 98
> [6,] 38 78 43
> [7,] 79 88 60
> [8,] 6 89 43
>
>
> I see how I can get the max on each row as:
>
> > apply(m, 1, max)
> [1] 75 82 72 88 98 78 88 89
>
> I want to generate a vector with the column position of each row max.
>
> The whole vector for the matrix shown above would be:
> 1 1 1 1 3 2 2 2
>
> Is there some easy, straightforward way to compute such a thing short of
> looping over the rows and columns of the matrix?
>
> Thanks,
> -ej
>
>
>
>
>
> --
> View this message in context:
>
http://r.789695.n4.nabble.com/Learning-to-speak-R-simple-data-processing-tp4655194.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Gregory (Greg) L. Snow Ph.D.
538280@gmail.com
[[alternative HTML version deleted]]