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().
sort(x, decreasing, na.last)
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.
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"