w3resource

R Programming: Find nth highest value in a given vector

R Programming: Vector Exercise-14 with Solution

Write a R program to find nth highest value in a given vector.

Sample Solution :

R Programming Code :

x = c(10, 20, 30, 20, 20, 25, 9, 26)
print("Original Vectors:")
print(x)
print("nth highest value in a given vector:")
print("n = 1")
n = 1
print(sort(x, TRUE)[n])
print("n = 2")
n = 2
print(sort(x, TRUE)[n])
print("n = 3")
n = 3
print(sort(x, TRUE)[n])
print("n = 4")
n = 4
print(sort(x, TRUE)[n])

Sample Output:

[1] "Original Vectors:"
[1] 10 20 30 20 20 25  9 26
[1] "nth highest value in a given vector:"
[1] "n = 1"
[1] 30
[1] "n = 2"
[1] 26
[1] "n = 3"
[1] 25
[1] "n = 4"
[1] 20                         

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to find second highest value in a given vector.
Next: Wrtie a R program to find common elements from multiple vectors.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.