R Program to find second highest value in a given vector

How to access the second highest value in a given vector

Here we are explaining how to write an R program to access the second-highest value in a given vector. For that first, 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.

Here we are using a built-in function sort() for this finding. The sort() function helps to sort a vector by its values. Sorting can be possible in both ascending and descending order. By default, it sorts in ascending order, for making sorting in descending order we need to set decreasing=TRUE. The syntax of sorting is like

sort(x, decreasing, na.last)  #Where x is a vector

Here x is the vector to be sorted, decreasing is the Boolean value to sort in descending order, and na.last is the Boolean value to put NA at the end.

In R programming we can sort a vector partially as follows,

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

which means arranging the vector x such that it's first m position contains the m smallest elements but not necessarily in ascending order and the position m will have the corresponding sorted element of the vector x.

So 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

Below are the steps used in the R program to get the 2nd last value in a given vector. In this R program, we directly give 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 into the variable vect_values. Finally, call the 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.


STEP 1: Assign variable vect_values with vector values

STEP 2: First print original vector values

STEP 3: assign the length of the vector to len by using 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("Find second highest value in a given vector:")
len = length(vect_values)
print(sort(vect_values, partial = len-1)[len-1])



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