Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

i.e. what

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

is to

max()

but for

which.max()

Best,

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

like image 286
user189035 Avatar asked Apr 06 '11 15:04

user189035


People also ask

How do you find the highest and lowest value 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 top 3 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 min function in R?

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


1 Answers

One possible route is to use the index.return argument to sort. I'm not sure if this is fastest though.

set.seed(21)
x <- rnorm(10)
ind <- 2
sapply(sort(x, index.return=TRUE), `[`, length(x)-ind+1)
#        x       ix 
# 1.746222 3.000000
like image 169
Joshua Ulrich Avatar answered Sep 19 '22 12:09

Joshua Ulrich