Here we are explaining how to write an R program to access the nth 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.
In this R program, we directly give the values to built-in functions. For that first, we consider the nth position into the variable n and the vector value is assigned into the variable A. Finally, call the sort function as sort(A, TRUE)[n] for finding nth largest element.
A = c(15, 25, 35, 25, 24, 45, 47, 10)
print("Original Vectors:")
## [1] "Original Vectors:"
print(A)
## [1] 15 25 35 25 24 45 47 10
print("nth highest value in a given vector:")
## [1] "nth highest value in a given vector:"
print("n = 1")
## [1] "n = 1"
n = 1
print(sort(A, TRUE)[n])
## [1] 47
print("n = 2")
## [1] "n = 2"
n = 2
print(sort(A, TRUE)[n])
## [1] 45
print("n = 3")
## [1] "n = 3"
n = 3
print(sort(A, TRUE)[n])
## [1] 35
print("n = 4")
## [1] "n = 4"
n = 4
print(sort(A, TRUE)[n])
## [1] 25
A = c(150, 250, 350, 255, 240, 450, 470, 100)
print("Original Vectors:")
## [1] "Original Vectors:"
print(A)
## [1] 150 250 350 255 240 450 470 100
print("nth highest value in a given vector:")
## [1] "nth highest value in a given vector:"
print("n = 1")
## [1] "n = 1"
n = 1
print(sort(A, TRUE)[n])
## [1] 470
print("n = 2")
## [1] "n = 2"
n = 2
print(sort(A, TRUE)[n])
## [1] 450
print("n = 3")
## [1] "n = 3"
n = 3
print(sort(A, TRUE)[n])
## [1] 350
print("n = 4")
## [1] "n = 4"
n = 4
print(sort(A, TRUE)[n])
## [1] 255