tags:

views:

297

answers:

3

Hello,

R offers max and min, but I do not see a really fast way to find the another value in the order apart from sorting the whole vector and than picking value x from this vector.

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

Thanks

+12  A: 

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

n <- length(x)
sort(x,partial=n-1)[n-1]
Rob Hyndman
Arr, very good and it works in all cases, would not have thought about that, thanks!
+2  A: 

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)] )
Paolo
Nice thing about it being one row! Thank for adding it!
+1  A: 

Just playing here with Paolo's vector :)

x <- c(12.45,34,4,0,-234,45.6,4)

For the nth higher/lowest value in this vector

n=2
# lowest
x[rank(x)==rank(x)[order(rank(x))][n]][1]
# higher
x[rank(x)==rank(x)[order(rank(x),decreasing = TRUE)][n]][1]
gd047