R Program to find nth highest value in a given vector


February 9, 2023, Learn eTutorial
1559

How do we access the nth highest value in a given vector

To find the nth highest value using the R program, we need to sort the values in descending order, now the elements will be in order from highest to smallest. Now we can easily print the required highest value depending on the value of n.

Here we are using a built-in function sort().

  • The sort() is an in-built function that helps to sort a vector by its values. The sorting can be possible in both ascending and descending order. By default, this function sorts in ascending order, for sorting in descending order need to set decreasing=TRUE. The syntax is like

sort(x, decreasing, na.last)

  • x: is the vector to be sorted
  • decreasing: For sorting the values in descending order
  • na.last: helps to put NA at the last of the vector

How to find nth highest value in the R program

In this R program, we directly give the values to built-in functions. Declare a vector vect with values, and print the original values for the user. Read the value n from the user to find the nth highest value. Now, call the sort function as sort(vect, TRUE)[n] for finding the nth largest element.

For example, take a vector with values 15, 25, 35, 25, 24,45, 47, 10

print(paste(n,"th highest value is", sort(vect, TRUE)[n]))

in the program line, we sort the vector and print the nth value of that vector. After sorting the vector values will be 47 45 35 25 25 24 15 10. If n=1 then it will show the highest value of 47, for n=2 it shows the 2nd highest value 45, and so on.

ALGORITHM

STEP 1: Assign variable vect with vector values

STEP 2: First print original vector values

STEP 3: Read value of n from user to find nth highest value

STEP 4: Call the function sort as sort(vect, TRUE)[n] to sort array in descending order and print the nth value

R Source Code

                                          vect = c(15, 25, 35, 25, 24,45, 47, 10)
print("Original Vectors:")
print(vect)
print("Finding nth highest value in a given vector:")
n = as.integer(readline(prompt="Enter value for n "))
print(paste(n,"th highest value is", sort(vect, TRUE)[n]))
                                      

OUTPUT

 "Original Vectors:"
 15 25 35 25 24 45 47 10
 "Finding nth highest value in a given vector:"
 Enter value for n: 4
 "4 th highest value is 25"