sort

Basics

sort is a function that allows you to arrange an object into ascending or descending order. The relevant arguments include:

  • x: mandatory; an object that contains a numeric, complex, logical, or character vector.

  • partial: if not NULL, then a vector with indices that will have the correct sorted value.

  • decreasing: TRUE to yield decreasing vector, FALSE to yield increasing vector. Default is FALSE.

In most situations, you will want to fully sort your object, which is straightforward.

For partial sorting, you can select indices to display the correct sorted value at those indices, though no other elements are guaranteed to be sorted.

Partial sorting does guarantee two things:

  1. Everything to the left of the desired index will be smaller than or equal to the sorted element.

  2. Everything to the right of the desired index will be larger than or equal to the sorted element.

Again, the left and right subsections surrounding an index are not sorted. Partial sorting is quicker than regular sorting due to fewer elements being sorted, which can save considerable time when looking for specific placement in large data sets.


Examples

Given a vector, arrange it in ascending order.

Click to see solution
x <- c(1,3,2,10,4)
sort(x)
[1]  1  2  3  4 10

What is the descending order of the previous vector?

Click to see solution
x <- c(1,3,2,10,4)
sort(x, decreasing = TRUE)
[1] 10  4  3  2  1

Rearrange the words waffle, pancake, eggs, and bacon to be in alphabetical order.

Click to see solution
sort(c("waffle", "pancake", "eggs", "bacon"))
[1] "bacon"   "eggs"    "pancake" "waffle"

What is the 5th element in x, assuming x is sorted? Use both standard and partial sorting.

Click to see solution
x = c(15,7,7,8,7,13,6,12,7,12,5)
sort(x)
sort(x, partial=5)
[1]  5  6  7  7  7  7  8 12 12 13 15
[1]  5  7  6  7  7  7 13 12  8 12 15

As we can see, the fifth element is 7.