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 value x from this vector.

Is there a faster way to get the second highest value (e.g.)?

Thanks

Login

0 votes

To find the second highest value in vector **‘z’**, use the following function:

sort(z, decreasing = TRUE)[2]

For example:

z <- sample(c(1:1000), 100, rep = FALSE)

sort(z, decreasing = TRUE)[2]

[1] 984

**To find the third highest:**

sort(z, decreasing = TRUE)[3]

[1] 967

You can also use the **partial **argument in **sort **function to find the second highest value in a vector as follows:

z <- sample(c(1:1000), 100, rep = FALSE)

n <- length(z)

sort(z,partial=n-1)[n-1]

[1] 984