Fastest way to find second (third...) highest/lowest value in vector or column

jorgusch picture jorgusch · Mar 16, 2010 · Viewed 203.1k times · Source

R offers max and min, but I do not see a really fast way to find another value in the order, apart from sorting the whole vector and then picking a value x from this vector.

Is there a faster way to get the second highest value, for example?

Answer

Rob Hyndman picture Rob Hyndman · Mar 16, 2010

Use the partial argument of sort(). For the second highest value:

n <- length(x)
sort(x,partial=n-1)[n-1]