sort in R: How to Sort Vector using sort() Function

A vector in R is a one-dimensional list of values of the same basic data type, such as text or numeric. In data analysis, you can sort your data according to a certain variable in the dataset. In addition, you can arrange the data in ascending or descending order.

To sort a data frame in R, use the order() function. By default, sorting is Ascending. But we are not here to talk about data frame, and we will see how to sort a. vector in R.

sort in R

To sort a Vector in R, use the sort() function. By default, R will sort the vector in ascending order. However, you can add the decreasing argument to the function, explicitly specifying the sort order.


sort(data, decreasing = FALSE)


data: It is a data or vector that is an R object with a class or a numeric, complex, character, or logical vector. For, a numeric, complex, character or logical vector, or a factor.

decreasing: It is logical. Should the sort be increasing or decreasing? For the “radix” method, this can be a vector of length equal to the number of arguments in …. For the other methods, it must be length one. Not available for partial sorting.

Sort a Vector in Ascending Order

To sort a vector in ascending order in R, pass the decreasing = FALSE to the sort() function.

data <- c(11, 21, 19, 18, 46)

sort(data, decreasing = FALSE)


[1] 11 18 19 21 46

You can see from the output that the vector is sorted in ascending order.

Sort a Vector in Descending Order

To sort a vector in Descending order, use the decreasing = TRUE to the sort() function.

data <- c(11, 21, 19, 18, 46)

sort(data, decreasing = TRUE)


[1] 46 21 19 18 11

Please one thing to note that sort is not in place. This means that the original vector is not affected (sorted). Only a sorted version of it is returned.


To Sort or order a vector or factor (partially) into ascending (or descending) order, use the sort() method. For ordering along more than one variable, e.g., for sorting data frames, use the order() function.

That’s it for this tutorial.

Leave a Comment