Sort a Vector in ascending and descending Order in R Programming
R Programming: Vector Exercise-9 with Solution
Write a R program to sort a Vector in ascending and descending order.
Sample Solution :
R Programming Code :
# Create a numeric vector 'x' with elements 10, 20, 30, 25, 9, and 26
x = c(10, 20, 30, 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 sorting in ascending order
print("Sort in ascending order:")
# Sort vector 'x' in ascending order and print the result
print(sort(x))
# Print a message indicating sorting in descending order
print("Sort in descending order:")
# Sort vector 'x' in descending order and print the result
print(sort(x, decreasing=TRUE))
Output:
[1] "Original Vectors:" [1] 10 20 30 25 9 26 [1] "Sort in ascending order:" [1] 9 10 20 25 26 30 [1] "Sort in descending order:" [1] 30 26 25 20 10 9
Explanation:
- x = c(10, 20, 30, 25, 9, 26): Creates a numeric vector x with the elements 10, 20, 30, 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("Sort in ascending order:"): Prints the label "Sort in ascending order:" to indicate that the following output will show the vector sorted in ascending order.
- print(sort(x)): Sorts vector x in ascending order and prints the sorted vector.
- print("Sort in descending order:"): Prints the label "Sort in descending order:" to indicate that the following output will show the vector sorted in descending order.
- print(sort(x, decreasing=TRUE)): Sorts vector x in descending order and prints the sorted vector.
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 the minimum and the maximum of a Vector.
Next: Write a R program to test whether a given vector contains a specified element.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics