Here we are explaining how to write an R program to access the second-highest value in a given vector. Here we are using a built-in function sort() for this finding. The sort() function helps to sort a vector by its values. The sorting can be possible in both ascending and descending order. By default, it sorts in ascending order for making sorting in ascending order need to set decreasing=TRUE. The syntax of sorting is like
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.
Below are the steps used in the R program to get the 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 l and the vector value is assigned into the variable A. Finally, call the sort function as sort(x, partial = l-1)[l-1] for finding second largest element.
A = c(20, 32, 30, 10, 40, 25, 30, 27)
print("Original Vectors:")
## [1] "Original Vectors:"
print(A)
## [1] 20 32 30 10 40 25 30 27
print("Find second highest value in a given vector:")
## [1] "Find second highest value in a given vector:"
l = length(A)
print(sort(A, partial = l-1)[l-1])
## [1] 32
A = c(25, 39, 80, 25, 71, 19, 34, 61)
print("Original Vectors:")
## [1] "Original Vectors:"
print(A)
## [1] 25 39 80 25 71 19 34 61
print("Find second highest value in a given vector:")
## [1] "Find second highest value in a given vector:"
l = length(A)
print(sort(A, partial = l-1)[l-1])
## [1] 71