sort()

sort()

The sort() function will sort a vector (or a single column in a data frame) by a specific variable, in ascending order.


You can use the decreasing = TRUE argument with the sort() function to sort the data frame in descending order (be careful not to confuse this with the desc() argument which is used with the filter() function).

NOTE: The sort() function is similar to the arrange() function, however, sort() works with vectors (or a single column in a data frame), while arrange() works with data frames (see the arrange() function).

Example 1: 

For instance, when we use the sort() function to sort the values in this small vector, it will sort the values in ascending order (smallest to largest) by default, like so:

# Create a vector called 'myvector' and print it out
myvector <- c(45, 55, 34, 12, 18)
myvector
# Sort the values
sort(myvector)

Example output:
Output of code showing the sorted values of the vector

Example 2:

You can add the argument decreasing = TRUE to sort the vector in decreasing order.

# Create a vector called 'myvector' and print it out
myvector <- c(45, 55, 34, 12, 18)
myvector
# Sort the values in decreasing order
sort(myvector, decreasing = TRUE)

Example output:
Output of code showing the sorted values of the vector in decreasing order

Example 3:

You can use sort() with a data frame, however, it will only sort that column (unlike arrange(), which will sort the whole data frame).

# Sort the column of Thumb lengths in the Fingers data frame
# Use head() to only view the first 6 values
head(sort(Fingers$Thumb))

Example output:
Output of code showing the sorted values of the Thumb
    • Related Articles

    • arrange()

      The arrange() function will arrange a data frame by a specific variable, in ascending order. You can use the desc() argument with the arrange() function to arrange the data frame in descending order. NOTE: The arrange() function is similar to the ...
    • desc()

      The desc() function can be used with the arrange() function to arrange a variable in a data frame in descending order. Example 1:  For instance, when we use the arrange() function to sort the Fingers data frame by Thumb, it will sort the values for ...
    • Five-Number Summary

      The 5-number summary is a way to describe the spread of a distribution around a median. If we start by sorting the values from smallest to largest, then chunk our data into quartiles (four equal groups of data points) we can get the five-number ...
    • quartiles

      Quartiles are the result of sorting quantitative variables and dividing the observations into four groups of equal sizes.
    • median

      Median is the middle number when numbers are sorted in order.