Ueli Hofstetter
Ueli Hofstetter

Reputation: 2534

How to get the second smallest/largest element in a list

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?

Upvotes: 1

Views: 4621

Answers (1)

janos
janos

Reputation: 124704

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]

Upvotes: 3

Related Questions