R Program to find second highest value in a given vector


February 8, 2023, Learn eTutorial
1793

How to find the second-highest value

For finding the second-highest value in R, we will sort the vector in ascending order and we can pick the 2nd highest value that will be at the 2nd last position of the sorted vector.

For that, we are using sort() function. The sort() is an in-built function in R that helps to sort a vector in both ascending and descending order. By default, it is in ascending order, for making sorting in descending order we need to set decreasing=TRUE. The syntax is like

sort(x, decreasing, na.last)

where, 

  • x is the vector to be sorted
  • decreasing: for sorting in decreasing order,
  • na.last is to put NA at the end.

In R programming we can sort partially as follows,

  • sort(x, partial=m)  
    x is a vector
    partial a vector of indices
    
    

which means arranging the vector 'x' such that it is first 'm' position contains the 'm' smallest elements but not necessarily in ascending order. Here, we will use partial sorting to find the second-highest value with partial= length-1 of vector x in sort() function.

How to find the second-highest value of a vector in the R program

In this R program, we are passing the values to built-in functions. For that first, we find the length of the vector into variable len and the vector value is assigned to the variable vect_values. Finally, call the partial sort function as sort(vect_values, partial = len-1) for finding the second largest element and print [len-1] th element of the sorted vector.

ALGORITHM

STEP 1: Assign variable vect_values with vector values

STEP 2: First print original values

STEP 3: assign the length of the vector to len by using the length function as length(vect_values)

STEP 4: Call the function sort as sort(vect_values, partial = len-1)

STEP 5: print the [len-1] th element of the sort() function

R Source Code

                                          vect_values = c(20, 32, 30, 10, 40, 25, 30, 27)
print("Original Vectors:")
print(vect_values)
print("Find second highest value in a given vector:")
len = length(vect_values)
print(sort(vect_values, partial = len-1)[len-1])

                                      

OUTPUT

[1] "Original Vectors:"
[1] 20, 32, 30, 10, 40, 25, 30, 27
[1] "Find second highest value in a given vector:"
[1] 32