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.
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
 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)
 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)
 "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)
 2 4 5  2 4 5 NA  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)
 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  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
 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.
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.
My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Name of the university: HUST