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.
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.
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
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]))
"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"