Find Second Highest / Lowest Value of Vector in R (2 Examples)
In this article you’ll learn how to return the second highest and lowest values in the R programming language.
Example Data
my_vec <- c(51, 13, - 17, 5, 0, 22, -3, 12) # Our example vector my_vec # Returning example vector to console # 51 13 -17 5 0 22 -3 12 |
my_vec <- c(51, 13, - 17, 5, 0, 22, -3, 12) # Our example vector my_vec # Returning example vector to console # 51 13 -17 5 0 22 -3 12
Example 1: Apply sort() & length() Functions to Get Second Highest / Lowest Value in Vector
sort(my_vec)[length(my_vec) - 1] # Second highest value # 22 |
sort(my_vec)[length(my_vec) - 1] # Second highest value # 22
sort(my_vec)[2] # Second lowest value # -3 |
sort(my_vec)[2] # Second lowest value # -3
Example 2: Apply sort() & length() Functions to Get Third Highest / Lowest Value in Vector
sort(my_vec)[length(my_vec) - 2] # Third highest value # 13 |
sort(my_vec)[length(my_vec) - 2] # Third highest value # 13
sort(my_vec)[3] # Third lowest value # 0 |
sort(my_vec)[3] # Third lowest value # 0