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

r, vector

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?

Best Solution

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

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