Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

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

1 Answer

0 votes
by
edited by

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

Browse Categories

...