To sort a vector in descending order in R, you can use the sort
function with the decreasing = TRUE
parameter.
In this example,
vec
with several numeric values.sort
function to sort the vector vec
in descending order by setting the decreasing = TRUE
parameter. This function sorts the elements of the vector in descending order.# Step 1: Create a numeric vector
vec <- c(5, 2, 8, 3, 9, 1)
# Step 2: Sort the vector in descending order
sorted_vec <- sort(vec, decreasing = TRUE)
# Step 3: Print the sorted vector
print(sorted_vec)
[1] 9 8 5 3 2 1
In this example,
vec
containing several string values.sort
function to sort the vector vec
in descending order by setting the decreasing = TRUE
parameter. This function sorts the elements of the vector in descending order based on lexicographic order.# Step 1: Create a character vector
vec <- c("apple", "banana", "orange", "grape", "kiwi")
# Step 2: Sort the vector in descending order
sorted_vec <- sort(vec, decreasing = TRUE)
# Step 3: Print the sorted vector
print(sorted_vec)
[1] "orange" "kiwi" "grape" "banana" "apple"
In this tutorial, we learned How to Sort a Vector in Descending Order in R language with well detailed examples.