w3resource

Find the Second Highest Value in a Vector using R Programming


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

Sample Solution :

R Programming Code :

 # Create a numeric vector 'x' with elements 10, 20, 30, 20, 20, 25, 9, and 26
x = c(10, 20, 30, 20, 20, 25, 9, 26)

# Print a message indicating the display of the original vector
print("Original Vectors:")

# Print the contents of vector 'x'
print(x)

# Print a message indicating the operation to find the second highest value
print("Find second highest value in a given vector:")

# Calculate the length of vector 'x'
l = length(x)

# Sort vector 'x' and print the second highest value by indexing
print(sort(x, partial = l-1)[l-1])

Output:

[1] "Original Vectors:"
[1] 10 20 30 20 20 25  9 26
[1] "Find second highest value in a given vector:"
[1] 26                         

Explanation:

  • x = c(10, 20, 30, 20, 20, 25, 9, 26): Creates a numeric vector x with the elements 10, 20, 30, 20, 20, 25, 9, and 26.
  • print("Original Vectors:"): Prints the label "Original Vectors:" to indicate that the following output will display the vector x.
  • print(x): Prints the contents of vector x.
  • print("Find second highest value in a given vector:"): Prints the label "Find second highest value in a given vector:" to indicate that the following output will show the second highest value in vector x.
  • l = length(x): Calculates the length of vector x and assigns it to variable l.
  • print(sort(x, partial = l-1)[l-1]):
    • sort(x, partial = l-1): Sorts the vector x and ensures the element at position l-1 (second last position) is included in the sorting.
    • [l-1]: Retrieves the second last element from the sorted vector, which is the second highest value.
    • Prints the second highest value from vector x.

R Programming Code Editor:



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

Previous: Write a R program to access the last value in a given vector.
Next: Write a R program to find nth highest value in a given vector.

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.