 # 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. To find the nth highest value of a vector first we need to sort the values in descending order, now the elements will be in the order from highest to the smallest so we can easily print the required highest value as the user wants to be found.

Here we are using a built-in function sort() for sorting the given vector. The sort() function 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 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 of the vector.

## 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. Declare a vector vect with values, and print them 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]))``
` `

It is the program line where 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 the1st highest value 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"

```
VIEW ALL
VIEW ALL
VIEW ALL