R Program to find nth highest value in a given vector

How to access the nth highest value in a given vector

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

sort(x, decreasing, na.last)

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.

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

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.

ALGORITHM

  • STEP 1: Assign variable A with vector values
  • STEP 2: First print original vector values
  • STEP 3: assign position variable n with 1,2,3,4 in each of the cases
  • STEP 4: Call the function sort as sort(A, TRUE)[n] by changing n values
  • STEP 5: print the result of the function

R Source Code

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

R Source Code

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