0

I am trying to rank the values of a row. I am trying to see which value is largest, which is second largest etc etc.

Here is a simple example:

test = c(0.005,0.007,0.009,-0.0008,0.5,-0.074)
order(test)
[1] 6 4 1 2 3 5
which.max(test)
[1] 5

The function which.max correctly gives me the column with the largest value, but it doesn't give me the second largest, third largest etc., etc.

I believed I could use the function order for this, but the output of that doesn't seem to be correct.

What am I doing wrong?

Thomas
  • 43,637
  • 12
  • 109
  • 140
  • http://stackoverflow.com/questions/2453326/fastest-way-to-find-second-third-highest-lowest-value-in-vector-or-column – GSee Aug 19 '13 at 16:35

2 Answers2

0

You just have to use the decreasing parameter:

> order(test,decreasing=T)
[1] 5 3 2 1 4 6

Or alternatively reverse it:

> rev(order(test))
[1] 5 3 2 1 4 6
David
  • 9,284
  • 3
  • 41
  • 40
  • Hi david, thank you very much for you reponse! This was was one of the first things I tried but it doesn't seem to work. If I use decreasing it still shows 0.5 as the fourth largest while clearly it is the largest value(which is confirmed by which.max). The order it should be is [1] 4 3 2 5 1 6. Or am I completely misunderstanding the order function? – user2690001 Aug 19 '13 at 16:55
  • I'm sorry but I don't understand what you're saying. 0.5 is the maximum and at index 5, which is why it is returned as the first index in the order call. When you use those indices to reference your vector (ie: the same as calling `sort()`) you'll see that they the vector has been sorted. Is there something inaccurate about that sorting? > `test[order(test,decreasing=T)]` --> 0.5000 0.0090 0.0070 0.0050 -0.0008 -0.0740 – David Aug 19 '13 at 17:09
  • Dear David, Thank you very much, now I understand! I indeed misunderstood the order function! This will do perfectly! – user2690001 Aug 19 '13 at 17:12
0

If you are looking for the values and not for the indices, then you should use sort

 sort(test,decreasing =TRUE)
    [1]  0.5000  0.0090  0.0070  0.0050 -0.0008 -0.0740
Metrics
  • 15,172
  • 7
  • 54
  • 83