To sort a vector in R, you can use the sort
function. This function allows you to sort the elements of a vector in either ascending or descending order.
In this example,
vec
with several numeric values.sort
function to sort the vector in ascending order. The sort
function takes the vector as an argument and returns a new vector with the elements sorted in ascending order.sort
function to a new variable named sorted_vec
to store the sorted vector.print
function.vec <- c(5, 2, 8, 3, 9, 1)
# Sort the vector in ascending order
sorted_vec <- sort(vec)
# Print the sorted vector
print(sorted_vec)
[1] 1 2 3 5 8 9
In this example,
vec
with several numeric values.sort
function to sort the vector in descending order. The sort
function takes the vector as an argument and an optional parameter decreasing
set to TRUE
to sort the elements in descending order.sort
function to a new variable named sorted_vec
to store the sorted vector.print
function.vec <- c(5, 2, 8, 3, 9, 1)
# Sort the vector in descending order
sorted_vec <- sort(vec, decreasing = TRUE)
# Print the sorted vector
print(sorted_vec)
[1] 9 8 5 3 2 1
In this tutorial, we learned How to Sort a Vector in R language with well detailed examples.