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

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)[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)[3]                                # Third lowest value
# 0

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top