Vector Sorting

To sort a vector in R programming, call sort() function and pass the vector as argument to this function. sort() function returns the sorted vector in increasing order.

The default sorting order is increasing order. We may sort in decreasing order using rev() function on the output returned by sort(). rev() reverses the order of vector.

In this tutorial, we will learn how to use sort() function to sort atomic vectors like integer vectors, double vectors, character vectors and logical vectors.

Syntax

The syntax of sort() function to sort a vector x is

</>
Copy
sort(x)

Return Value

The function returns a vector with contents of the x sorted.

Examples

In the following example programs, we cover sorting integer, double, character and logical vectors.

Sort Integer Vector

In the following program, we take an integer vector in x, and sort this vector in increasing order using sort() function. We print the original vector and the sorted vector returned by sort() function.

example.R

</>
Copy
x <- c(2L, 1L, 4L, 3L)
result <- sort(x)
cat("Original Vector :", x, "\n")
cat("Sorted   Vector :", result)

Output

Original Vector : 2 1 4 3 
Sorted   Vector : 1 2 3 4

Now, we shall sort the vector in descending order, using rev() function.

example.R

</>
Copy
x <- c(2L, 1L, 4L, 3L)
result <- rev(sort(x))
cat("Original Vector :", x, "\n")
cat("Sorted   Vector :", result)

Output

Original Vector : 2 1 4 3 
Sorted   Vector : 4 3 2 1

The result is a vector sorted in descending order.

Sort Double Vector

In the following program, we take a double vector in x, and sort this vector in increasing order using sort() function.

example.R

</>
Copy
x <- c(2, 1, 4, 3)
result <- sort(x)
cat("Original Vector :", x, "\n")
cat("Sorted   Vector :", result)

Output

Original Vector : 2 1 4 3 
Sorted   Vector : 1 2 3 4

Sort Character Vector

In the following program, we take a character vector in x, and sort this vector in increasing order using sort() function. For string values, increasing order means lexicographically increasing order. For example while sorting strings, “a” is less than “b”, “b” is less than “m” and so on.

example.R

</>
Copy
x <- c("b", "a", "d", "c")
result <- sort(x)
cat("Original Vector :", x, "\n")
cat("Sorted   Vector :", result)

Output

Original Vector : b a d c 
Sorted   Vector : a b c d

Sort Logical Vector

In the following program, we take an logical vector in x, and sort this vector in increasing order using sort() function. Logical value TRUE is greater than logical value FALSE.

example.R

</>
Copy
x <- c(TRUE, FALSE, FALSE, TRUE)
result <- sort(x)
cat("Original Vector :", x, "\n")
cat("Sorted   Vector :", result)

Output

Original Vector : TRUE FALSE FALSE TRUE 
Sorted   Vector : FALSE FALSE TRUE TRUE

Conclusion

In this R Tutorial, we learned how to sort a vector, using sort() function, with the help of examples.