The functions which.min() and which.max() can be used to find the indeces of the smallest and largest elements, e.g.:

data(iris)
smallest <- which.min(iris$Sepal.Length)
iris[smallest, ]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
14 4.3 3 1.1 0.1 setosa
largest <- which.max(iris$Sepal.Length)
iris[largest, ]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
132 7.9 3.8 6.4 2 virginica

To find the \(n\) smallest or largest elements, use the function order():

n <- 5

smallest <- order(iris$Sepal.Length)[1:n]
iris[smallest, ]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
14 4.3 3.0 1.1 0.1 setosa
9 4.4 2.9 1.4 0.2 setosa
39 4.4 3.0 1.3 0.2 setosa
43 4.4 3.2 1.3 0.2 setosa
42 4.5 2.3 1.3 0.3 setosa
largest <- order(iris$Sepal.Length, decreasing = TRUE)[1:n]
iris[largest, ]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
132 7.9 3.8 6.4 2.0 virginica
118 7.7 3.8 6.7 2.2 virginica
119 7.7 2.6 6.9 2.3 virginica
123 7.7 2.8 6.7 2.0 virginica
136 7.7 3.0 6.1 2.3 virginica

Last updated: 2019-12-10

Back to the front page