[R] which.max2()

Marc Schwartz marc_schwartz at comcast.net
Fri May 9 17:11:15 CEST 2008


on 05/09/2008 08:07 AM Esmail Bonakdarian wrote:
> Hello,
> 
> which.max() only returns one index value, the one for the
> maximum value. If I want the two index values for the two
> largest values, is this a decent solution, or is there a
> nicer/better R'ish way?
> 
> max2 <-function(v)
> {
>     m=which.max(v)
>     v[m] = -v[m]
>     m2=which.max(v)
>     result=c(m, m2)
>     result
> }
> 
> Seems to work ok.
> 
> Thanks,
> Esmail

I might be tempted to take a more generic approach, where one can
provide an argument to the function to indicate that I want the 'top x'
maximum values and to give the user the option of returning the indices 
or the values themselves.

Perhaps:

which.max2 <- function(x, top = 1, values = FALSE)
{
   if (values)
     rev(sort(x))[1:top]
   else
     order(x, decreasing = TRUE)[1:top]
}

set.seed(1)
Vec <- rnorm(10)

 > Vec
  [1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078 -0.8204684
  [7]  0.4874291  0.7383247  0.5757814 -0.3053884


 > which.max2(Vec, 2)
[1] 4 8

 > which.max2(Vec, 2, values = TRUE)
[1] 1.5952808 0.7383247


HTH,

Marc Schwartz



More information about the R-help mailing list