How To Sort Vector in R?
We user sort() function to sort a vector in R programming and pass the vector as argument to the function. By default, sort() function returns vector sorted in increasing order or ascending.
We may sort in decreasing order using rev() function which reverse the order of vector on the output returned by sort().
Sort() function is applicable to sort items in vector not only for integer vectors, but also for double vectors, character vectors and logical vectors.
The Syntax:
sort(x) |
Example – Sort Integer Vector:
m <- c(30L, 10L, 45L, 11L)
result1 <- sort(m)
result2 <- rev(sort(m))
cat("Sorted Vector ascending:", result1)
cat("Sorted Vector descending:", result2)
#output:
Sorted Vector ascending: 10 11 30 45
Sorted Vector descending: 45 30 11 10
Example – Sort Double Vector:
m <- c(30, 10, 45, 11)
result1 <- sort(m)
result2 <- rev(sort(m))
cat("Sorted Vector ascending:", result1)
cat("Sorted Vector descending:", result2)
#output:
Sorted Vector ascending: 10 11 30 45
Sorted Vector descending: 45 30 11 10
Example – Sort Character Vector:
m <- c("p", "q", "r", "s")
result1 <- sort(m)
result2 <- rev(sort(m))
cat("Sorted Vector ascending:", result1)
cat("Sorted Vector descending:", result2)
#output:
Sorted Vector ascending: p q r s
Sorted Vector descending: s r q p
Example – Sort Logical Vector:
m <- c(TRUE, FALSE, FALSE, TRUE)
result1 <- sort(m)
result2 <- rev(sort(m))
cat("Sorted Vector ascending:", result1)
cat("Sorted Vector descending:", result2)
#output:
Sorted Vector ascending: FALSE FALSE TRUE TRUE
Sorted Vector descending: TRUE TRUE FALSE FALSE
Conclusion:
To sort items of vector is done by calling the sort() function for ascending and rev() function for descending order.
