![]() |
VOOZH | about |
Prerequisite: R – Array
A vector is a uni-dimensional array, which is specified by a single dimension, length. A Vector can be created using the ‘c()‘ function. A list of values is passed to the c() function to create a vector. Sorting can be done either in ascending order or descending. There are few things which should be kept in mind before sorting. They are as follows:
sort() function in R is used to sort a vector. By default, it sorts a vector in increasing order. To sort in descending order, add a "decreasing" parameter to the sort function.
Syntax:
sort(name_of_vector, decreasing = TRUE)
Parameters:
name_of_vector: Vector to be sorted
decreasing: Boolean value to sort in descending order
Example 1:
Output:
[1] 1 2 3 4 5 6 7 8 9
Example 2:
Output:
[1] 9 8 7 6 5 4 3 2 1
Note: The major drawback of the sort() function is that it cannot sort data frames.
To overcome the drawback in method 1, we use the order() function, which also sorts data frames according to the specified column. To sort in decreasing order add negative sign. Data can also be sorted with multiple criteria. Suppose if the age of two persons is the same then, we can sort them on the basis of their names i.e. lexicographically. See the below examples.
Example 1:
Output:
Age Name 4 5 Jack 1 12 Johnny 3 15 Alfie 2 21 Glen 5 25 Finch
Example 2:
Output:
[1] 6 5 4 3 2 1
Example 3:
Output:
Age Name 6 12 Aaron 4 12 Jack 1 12 Johnny 3 15 Alfie 2 21 Glen 5 25 Finch
Note: The output above is the indices of numbers. For instance, 60 is the largest in vector and had index 6. Thus, 6 is displayed first.
Below is the implementation of the above approach.
Output:
[1] 1 2 3 4 4 5 5 6 9
dplyr package is easy to use and reliable. The package includes arrange() method to sort the data. See the below examples.
Example 1:
Output:
Age Name 4 5 Jack 1 12 Johnny 3 15 Alfie 2 21 Glen 5 25 Finch