How to sort a vector in R programming language
In this tutorial, we are going to learn about how to sort a vector in R language with the help of examples.
To sort a vector in R language, we can use the built-in sort() function.
The sort() function takes the vector as an argument and returns the sorted items in ascending order for strings it will return alphabetical order.
Here is an example, that sorts the vector of numbers in ascending order :
# vector of numbers
prices = c(5, 3, 6, 2)
result = sort(prices)
print(result)
Output:
[1] 2 3 5 6
In the example above, we have sorted the vector of numbers in ascending order.
To sort a vector in descending order, we can use the sort() function by passing the second argument as a “decreasing” boolean.
Here is an example, that sorts the vector in descending order:
# vector of numbers
prices = c(5, 3, 6, 2)
result = sort(prices, decreasing= TRUE)
print(result)
Output:
[1] 6 5 3 2