1

I am looking for a way to get the second(third, fourth etc.) smallest/ largest element of a list in R. Using which.min / which.max I came up with the following solution for the second largest element:

test <- c(9,1,3,5,2,4,10)
(test[-which.max(test)])[which.max(test[-which.max(test)])]]

However, this is ugly and does not really scale up. Is there a better way to get the x smallest/largest element/value of a list?

Ueli Hofstetter
  • 2,409
  • 4
  • 29
  • 52
  • 1
    http://stackoverflow.com/questions/2453326/fastest-way-to-find-second-third-highest-lowest-value-in-vector-or-column this looks relevant, but I'm still not seeing any of the O(n) solutions implemented, partial sort is still O(nlogn) – Shape May 06 '16 at 22:50

1 Answers1

3

You can use sort, and then an index, to find the n-th smallest element:

sort(test)[n]

For the second smallest element, use n=2:

sort(test)[2]
janos
  • 120,954
  • 29
  • 226
  • 236
  • 1
    Of course :-) And to get the index combining it with match works perfectly. match(sort(test, decreasing=TRUE)[2],test). Thx. – Ueli Hofstetter May 06 '16 at 20:25
  • this answer certainly works, but if you're sorting to find just one element, it seems like you're being a bit inefficient. Searching for the nth highest element should be O(N), not O(nlogn) – Shape May 06 '16 at 22:02