Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (7.3k points)

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.)?


1 Answer

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)


[1] 984

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94.1k users

Browse Categories