How To Use The sort Function In R

The sort function in R can sort numeric and character vectors in your desired order. It is a simple version of more complex sorting functions in this language. Follow the examples below to understand the way this function sorts vectors.

Table of Contents

sort Function In R

In the R programming language, the sort() function sorts the elements of a vector in ascending or descending order. This can be useful for arranging the elements of a vector in a particular order, such as alphabetically or numerically.

Bear in mind that this function can only sort one variable at a time. If you have a data frame, for example, and want to sort its data using multiple variables, check out the order() function.

Here’s an example of using sort() with a simple R vector:

x = c(13, 52, 4, 24)
x1 = sort(x)
x1

Output

[1] 4 13 24 52

In the above example, we create a vector x containing four numbers. Then we pass x as the sole argument of the sort() function, telling it to sort the vector and store the result in a new variable called x1.

As you may notice, sort() uses the ascending order by default. This is because the default value of the decreasing argument is FALSE. You can set it to TRUE if you want to sort() a vector in descending order:

sort(x, decreasing = TRUE)

Output

[1] 52 24 13 4

In addition to numeric vectors, the sort() function also works with character values. With such arguments, it works in an alphabetical manner.

 x = c("learnshareit", "reddit", "quora") 
 sort(x)

Output

[1] "learnshareit" "quora" "reddit"      

When sort() encounters NA values, its default behavior is to remove them from the sorting. However, you can set the na.last argument to TRUE or FALSE if you want to keep them. These NA values will be added to the last if na.last = TRUE and first otherwise.

x = c(4, 2, NA, 5)
sort(x)
sort(x, na.last = TRUE)
sort(x, na.last = FALSE)

Output

[1] 2 4 5
[1] 2 4 5 NA
[1] NA 2 4 5

While sort() can be used on data frames, you can sort columns with it. Here is a sample from the built-in mtcars dataset. We extract some rows and sort the mpg and cyl columns with sort():

df <- head(mtcars)
sort(mtcars$mpg)

Output

[1] 10.4 10.4 13.3 14.3 14.7 15.0 15.2 15.2 15.5 15.8 16.4 17.3 17.8 18.1 18.7 19.2 19.2
[18] 19.7 21.0 21.0 21.4 21.4 21.5 22.8 22.8 24.4 26.0 27.3 30.4 30.4 32.4 33.9
sort(mtcars$cyl)
 [1] 4 4 4 4 4 4 4 4 4 4 4 6 6 6 6 6 6 6 8 8 8 8 8 8 8 8 8 8 8 8 8 8

Note: read this guide to learn more about the head() function.

Summary

Use the sort function in R when you need to simply sort numeric or character elements of a vector. There are different sorting behaviors you can adjust with sort(), including the sorting method and order.

Posted in R

Leave a Reply

Your email address will not be published. Required fields are marked *