Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 519
jorgusch Avatar asked Mar 16 '10 09:03

jorgusch


People also ask

How do you find the highest and lowest values in R?

We can find the minimum and the maximum of a vector using the min() or the max() function. A function called range() is also available which returns the minimum and maximum in a two element vector.

How do you find the highest value in a vector in R?

max() in R The max() is a built-in R function that finds the maximum value of the vector or data frame. It takes the R object as an input and returns the maximum value out of it. To find the maximum value of vector elements, data frame, and columns, use the max() function.

How do you find the top 5 values in R?

To get the top values in an R data frame, we can use the head function and if we want the values in decreasing order then sort function will be required. Therefore, we need to use the combination of head and sort function to find the top values in decreasing order.

What is the max function in R?

which. max() function in R Language is used to return the location of the first maximum value in the Numeric Vector.


2 Answers

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

n <- length(x) sort(x,partial=n-1)[n-1] 
like image 123
Rob Hyndman Avatar answered Sep 28 '22 22:09

Rob Hyndman


Slightly slower alternative, just for the records:

x <- c(12.45,34,4,0,-234,45.6,4) max( x[x!=max(x)] ) min( x[x!=min(x)] ) 
like image 33
Paolo Avatar answered Sep 28 '22 22:09

Paolo