Sorting of Arrays in R Programming
Last Updated :
12 Jul, 2021
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:
- Order in which sorting needs to be performed - Ascending/Descending.
- Sorting according to multiple column criteria.
- Handling missing and duplicate values during sorting. The analyst must decide what should be done with missing and duplicate values. The overall impact on the data should be considered before removing or replacing null values.
Method 1: sort() function
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:
R
# create a linear array
arr <- c(9, 8, 7, 6, 5, 4, 3, 2, 1)
# use of sort function to sort array
# by default it is sorted in increasing order
sort(arr)
Output:
[1] 1 2 3 4 5 6 7 8 9
Example 2:
R
# create linear array
arr <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
# use in built sort function
# to sort in decreasing order
sort(arr, decreasing = TRUE)
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.
Method 2: order() function
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:
R
# define dataframe
df <- data.frame("Age" = c(12, 21, 15, 5, 25),
"Name" = c("Johnny", "Glen", "Alfie",
"Jack", "Finch"))
# sort the dataframe on the basis of
# age column and store it in newdf
newdf <- df[order(df$Age), ]
# print sorted dataframe
print(newdf)
Output:
Age Name
4 5 Jack
1 12 Johnny
3 15 Alfie
2 21 Glen
5 25 Finch
Example 2:
R
# define vector
r = c(10, 20, 30, 40, 50, 60)
# sort in decreasing order
order(-r)
Output:
[1] 6 5 4 3 2 1
Example 3:
R
# define dataframe
df <- data.frame("Age" = c(12, 21, 15, 12, 25, 12),
"Name" = c("Johnny", "Glen", "Alfie",
"Jack", "Finch", "Aaron"))
# sort the dataframe first on the basis of
# Age and if age is same perform sort on Name
newdf <- df[order(df$Age, df$Name), ]
# print sorted dataframe
print(newdf)
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.
Method 3: Sorting array using the loop
- Create a linear array, say arr
- Create a variable swap. If swap is false after traversing the entire array, it means the array is already sorted and break the loop
- Else, run loop and copy original array into another array, say newArr, and start comparing adjacent elements in the original array
- If the current element is smaller than the previous element, then copy the current element of arr into the previous position of newArr and the previous element of arr into the current position of newArr. The newArr now has swapped elements.
- Copy newArr to original array arr and make swap = TRUE.
- Repeat until arr is sorted
Below is the implementation of the above approach.
R
# create linear array
arr <- c(9, 4, 5, 4, 5, 6, 3, 2, 1)
# repeat until break is encountered
repeat
{
# create a variable swap
swap = FALSE
# run loop from 2nd element till last element
for (i in 2:length(arr))
{
# copy original array into newArr
newArr <- arr
if (arr[i - 1] > arr[i])
{
newArr[i - 1] <- arr[i]
newArr[i] <- arr[i - 1]
arr <- newArr
swapped <- TRUE
}
}
if (!swapped) {break}
}
print(arr)
Output:
[1] 1 2 3 4 4 5 5 6 9
Method 4: The use of dplyr package
dplyr package is easy to use and reliable. The package includes arrange() method to sort the data. See the below examples.
Example 1:
R
# install package dplyr
install.packages("dplyr")
# import library dplyr
library(dplyr)
# create dataframe
df <- data.frame("Age" = c(12, 21, 15, 5, 25),
"Name" = c("Johnny", "Glen", "Alfie",
"Jack", "Finch"))
# sort the dataframe on the basis of
# age column using arrange method
arrange(df,age)
Output:
Age Name
4 5 Jack
1 12 Johnny
3 15 Alfie
2 21 Glen
5 25 Finch
Similar Reads
Types of Sorting Algorithm in R Programming There are multiple ways by which data can be sorted in the R language. Itâs up to the data Analyst to consider the most suitable method based upon the structure of the data. There are multiple algorithms for performing sorting on the data in the R programming language. Below different types of sorti
6 min read
Array vs Matrix in R Programming The data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Data structures in R programming are tools for holding multiple values. The two most important data structures in R ar
3 min read
Array Operations in R Programming Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-dimensional data structures. For example, if we create an array of dimensions (2, 3, 3) then it creates 3 rectangular matrices each with 2 rows and 3 columns. They are homogeneous data structures. Now, letâs
4 min read
Sorting of a Vector in R Programming - sort() Function In R Programming Language we can sort a vector in ascending or descending order using the sort() function. The sort() function returns a sorted version of the input vector. sort() function in is used to sort a vector by its values. It takes the Boolean value as an argument to sort in ascending or de
2 min read
Reordering of a Data Set in R Programming - arrange() Function arrange() function in R Language is used for reordering of table rows with the help of column names as expression passed to the function. Syntax: arrange(x, expr) Parameters: x: data set to be reordered expr: logical expression with column name Example 1: Python3 1== # R program to reorder a data se
1 min read
Organising Data in R Organizing data is a fundamental step in data analysis and manipulation, and R Programming Language provides a powerful set of tools and techniques to help you efficiently structure and manage your data. Whether you're working with small datasets or massive datasets, understanding how to organize yo
5 min read
Sorting DataFrame in R using Dplyr In this article, we will discuss about how to sort a dataframe in R programming language using Dplyr package. The package Dplyr in R programming language provides a function called arrange() function which is useful for sorting the dataframe. Syntax :Â arrange(.data, ...) The methods given below sho
3 min read
NumPy Array Sorting | How to sort NumPy Array Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.ar
4 min read
Operations on Lists in R Programming Lists in R language, are the objects which comprise elements of diverse types like numbers, strings, logical values, vectors, list within a list and also matrix and function as its element. A list is generated using list() function. It is basically a generic vector that contains different objects. R
4 min read
Ordering Factor Values in R In this article, we will see how to order factor values in the R programming language. We can order Factor values using the as.ordered() method. It is available in dplyr() package. So we have to load this package. Syntax: library(dplyr)Â Syntax: as.ordered(factor_data) Example 1 : In this example, w
2 min read