To sort a vector in R, you can use the sort()
function. For sorting in ascending order, you simply call the sort()
function. For sorting in descending order, you can use the sort()
function with the decreasing
parameter set to TRUE
.
In this example,
numbers
with integer values.sort()
function to sort the vector in ascending order and store the sorted vector in the variable sorted_numbers
.sort()
function sorts the elements in natural order.numbers <- c(5, 2, 8, 1, 3)
sorted_numbers <- sort(numbers)
cat("Sorted vector in ascending order:", sorted_numbers)
Sorted vector in ascending order: 1 2 3 5 8
In this example,
numbers
with integer values.sort()
function with the decreasing
parameter set to TRUE
to sort the vector in descending order and store the sorted vector in the variable sorted_numbers
.sort()
function with decreasing=TRUE
sorts the elements in reverse natural order.numbers <- c(5, 2, 8, 1, 3)
sorted_numbers <- sort(numbers, decreasing = TRUE)
cat("Sorted vector in descending order:", sorted_numbers)
Sorted vector in descending order: 8 5 3 2 1
In this tutorial, we learned How to Sort a List in R language with well detailed examples.