Open In App

Arrange rows in ascending and descending order using R

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to discuss “How we can arrange rows of a data frame in both ascending and descending order” in R Programming Language.

What are data frames?

In R programming language, we use data frames to store data. In simple words, “A data frame is a 2-dimensional array that stores data and displays it in the form of a table”.As the name suggests, A data frame is something that stores the data as an array that is framed as a proper tabular structure. In other words, framing data in a structured manner. A data frame can have different types of data in it which means it is useful for heterogeneous data types.

How is it displayed?

As we’ve discussed in the “Introduction” section it is displayed in the form of a table. To be more specific, The data frame will be given a column name as specified by the programmer, and the data are entered into it and each entry/row is given a row number.

Operations that can be performed on a data frame

  1. We use data.frame() to create a data frame.
  2. We can use summary() function to summarize the data in the data frame.
  3. We can use single brackets [], double brackets [[]]] and $ symbol to access the data in the data frame.
  4. We use rbind() function to add a new row and cbind() function to add a new column.
  5. We use the dim() function to find the dimension of rows and columns in a data frame.
  6. We use the ncol() function to find the number of columns and nrow() to find the number of rows in the data frame.

Ascending and Descending Order of Rows

As we’ve discussed earlier, the data is displayed in the form of a table with rows and columns. In R the data frame is given a row number implicitly. In this article we will be going through the examples of how we can arrange this row numbers in ascending and descending order. The following examples will make this even more clearer.

We could not only arrange the rows of a data frame in ascending and descending order but, also the rows of a matrix. We will be using the order() function in Example-5 to arrange the rows of a matrix.

R




products_data <- data.frame(
  ProductID = c(101, 102, 103, 104),
  Name = c("Laptop", "Phone", "Tablet", "Headphones"),
  Price_INR = c(30000, 15000, 13000, 1500)
)
 
print(products_data)


Output:

  ProductID       Name Price_INR
1 101 Laptop 30000
2 102 Phone 15000
3 103 Tablet 13000
4 104 Headphones 1500

We created a data frame using data.frame() function. In this example the data frame is stored inside the variable named “products_data”.

  • Then, we created the columns using c() function. We say this as vectors, meaning.., the “ProductID” is a vector name and the c() will have its data.
  • Likewise.., we created 3 columns and now our sample data frame of products is over.
  • In the last line we print the data frame to display it.
  • In the output image.., you could see how the row numbers (1,2,3,4) are given implicitly (not specified by the programmer).

Syntax of the Functions:

In this article, we will be working with 2 major sorting functions that are used to sort/arrange the data frame or a matrix. The functions are order() and arrange(). Let us understand its syntax in this section before moving on with the examples.

Syntax for order():

Ascending: sorted_df <- data_frame[order(data_frame$column_name), ]

Descending: sorted_df_desc <- data_frame[order(data_frame$column_name, decreasing = TRUE), ]

Syntax for arrange():

library(dplyr)

ascending_df <- arrange(data_frame, column_name)

descending_df <- arrange(data_frame, desc(column_name))

  1. order() by default will order the data in ascending order.
  2. To order the data in descending order we can use the line “decreasing = TRUE” to arrange the data in decreasing order.
  3. We can also use the ‘-‘ sign inside the order() function and before the data frame name and column name to reverse the ascending order.
  4. The arrange() function is from the ‘dplyr’ package so it is essential to load it to use the arrange(). We usually load the packages in R using the library(package_name) function.
  5. arrange() will, by default arrange in ascending order but we can specify desc() function before the column name to arrange in descending order.

Ascending Order

R




# create a data frame with student info
students_data <- data.frame(
  StudentID = c("22CSE1", "22CSE2", "22CSE3", "22CSE4"),
  Name = c("Anitha", "Bharath", "Chitra", "Daksh"),
  Score = c(85, 92, 78, 96)
)
students_data
# Ascending Order
# Choosing the 'Score' column
score_column <- students_data$Score
# Rearrange the rows
students_asc <- students_data[order(score_column),]
 
# print the ordered rows and cols
print("Ascending Order based on Score:")
print(students_asc)


Output:

  StudentID    Name Score
1 22CSE1 Anitha 85
2 22CSE2 Bharath 92
3 22CSE3 Chitra 78
4 22CSE4 Daksh 96

[1] "Ascending Order based on Score:"

StudentID Name Score
3 22CSE3 Chitra 78
1 22CSE1 Anitha 85
2 22CSE2 Bharath 92
4 22CSE4 Daksh 96

In the above code snippet, we are starting off by creating a data frame using the data.frame() function.

  • Inside the data.frame() function we are creating a vector using the c() function. It is like saying.., create a column with the name StudentID and it will have values. These values are our choice or based on the data. To add those data values we use the c() function.
  • Once the data frame is created, we select the column based on which the rows are arranged. We can select the column using the ‘$’ symbol. Its syntax can be given as dataFrameName$columnName. Store it inside a variable.
  • Now, we can use the dataFrameName[order(selected column variableName),]. We store this info inside a variable.
  • Finally, print the variable.
  • We use comma after the order() function in order to select the whole data frame while printing the result.
  • In this snippet we have used the order() to arrange in ascending, In our next example we will look into descending order for the same data frame.

Descending Order

R




# create a data frame with student info
students_data <- data.frame(
  StudentID = c("22CSE1", "22CSE2", "22CSE3", "22CSE4"),
  Name = c("Anitha", "Bharath", "Chitra", "Daksh"),
  Score = c(85, 92, 78, 96)
)
students_data
# Descending Order
# Choosing the 'Score' column
score_column <- students_data$Score
# Rearrange the rows
# use '-' to reverse the order from ascending to descending
students_desc <- students_data[order(-score_column),]
 
# print the ordered rows and cols
print("Descending Order based on Score:")
print(students_desc)


Output:

  StudentID    Name Score
1 22CSE1 Anitha 85
2 22CSE2 Bharath 92
3 22CSE3 Chitra 78
4 22CSE4 Daksh 96

[1] "Descending Order based on Score:"

StudentID Name Score
4 22CSE4 Daksh 96
2 22CSE2 Bharath 92
1 22CSE1 Anitha 85
3 22CSE3 Chitra 78

In the above code snippet, we are starting off by creating a data frame using the data.frame() function.

  • Inside the data.frame() function we are creating a vector using the c() function. It is like saying.., create a column with the name StudentID and it will have values. These values are our choice or based on the data. To add those data values we use the c() function.
  • Once the data frame is created, we select the column based on which the rows are arranged. We can select the column using the ‘$’ symbol. Its syntax can be given as dataFrameName$columnName. Store it inside a variable.
  • Now, we can use the dataFrameName[order(-selected column variableName),]. We store this info inside a variable.
  • In this code, the only major difference is the minus sign inside the order() function.
  • Finally, print the variable.

Ascending and Descending Order

R




# data frame with book info
books_data <- data.frame(
  Title = c("Ikigai", "Let Us C", "1984", "Wings Of Fire"),
  Publication_Year = c(2016, 2008, 1949, 1999)
)
books_data
# Ascending Order based on Publication Year
year_asc <- order(books_data$Publication_Year)
books_asc <- books_data[year_asc, ]
 
# Descending Order based on Publication Year
year_desc <- order(books_data$Publication_Year, decreasing = TRUE)
books_desc <- books_data[year_desc, ]
 
# print the results
print("Ascending Order based on Publication Year:")
print(books_asc)
 
print("Descending Order based on Publication Year:")
print(books_desc)


Output:

          Title Publication_Year
1 Ikigai 2016
2 Let Us C 2008
3 1984 1949
4 Wings Of Fire 1999

[1] "Ascending Order based on Publication Year:"

Title Publication_Year
3 1984 1949
4 Wings Of Fire 1999
2 Let Us C 2008
1 Ikigai 2016

[1] "Descending Order based on Publication Year:"

Title Publication_Year
1 Ikigai 2016
2 Let Us C 2008
4 Wings Of Fire 1999
3 1984 1949

In the above code snippet, we first create a sample data frame.

  • We then order the required column using the order()function and the $ symbol to select the required column.
  • We now want to select the whole data frame so, we use the dataFrameName[ordered_variableName,] As we’ve discussed in the previous examples.., we use the ‘comma’ to select the whole data frame. We store this in a variable.
  • Now, we proceed with descending order.., In descending order the major inclusion is the decreasing = TRUE line inside the order() function and then a comma to select the whole data frame as usual.
  • Finally, we print the results.
  • This snippet is also equal to.., using the minus sign inside the order() function to reverse the order of data.

Ascending and Descending Order In a matrix

R




# Create the matrix
original_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE)
# print the original matrix
print("Original Matrix:")
print(original_matrix)
 
# Arrange rows in ascending order
ascending_order <- original_matrix[order(original_matrix[, 1]), ]
print("\nMatrix Rows in Ascending Order:")
print(ascending_order)
 
# Arrange rows in descending order
descending_order <- original_matrix[order(original_matrix[, 1], decreasing = TRUE), ]
print("\nMatrix Rows in Descending Order:")
print(descending_order)


Output:

[1] "Original Matrix:"
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6

[1] "Matrix Rows in Ascending Order:"

[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6

[1] "Matrix Rows in Descending Order:"

[,1] [,2] [,3]
[1,] 4 5 6
[2,] 1 2 3

In this snippet, we have created a matrix by nrow (number of rows) = 2 and byrow (the values will be filled by row) = TRUE.

  • We print the matrix to spot the difference later.
  • Now, we use the order() function to order the matrix.
  • In this snippet, we have used the “decreasing = TRUE” statement but we could also use the minus sign as discussed earlier.
  • We use [,1] to imply that select all rows from first column. All the rows of a column will be arranged in the required order.
  • Print the result at the end.

Ascending and Descending Order using arrange()

R




# Install and load the dplyr package
install.packages("dplyr")
library(dplyr)
 
# Creating a data frame
my_dataFrame <- data.frame(
  ID = c(1,2,3,4),
  Name = c("Priya", "Nithin", "Harini", "Jo"),
  Score = c(80, 90, 74, 91)
)
 
# Arranging rows in ascending order based on the Score column
arranged_data_asc <- arrange(my_dataFrame, Score)
 
# Arranging rows in descending order based on the Score column
arranged_data_desc <- arrange(my_dataFrame, desc(Score))
 
# Printing the results
print("Arranged Data Frame (Ascending Order based on Score):")
print(arranged_data_asc)
 
print("Arranged Data Frame (Descending Order based on Score):")
print(arranged_data_desc)


Output:

  ID   Name Score
1 1 Priya 80
2 2 Nithin 90
3 3 Harini 74
4 4 Jo 91

[1] "Arranged Data Frame (Ascending Order based on Score):"

ID Name Score
1 3 Harini 74
2 1 Priya 80
3 2 Nithin 90
4 4 Jo 91

[1] "Arranged Data Frame (Descending Order based on Score):"

ID Name Score
1 4 Jo 91
2 2 Nithin 90
3 1 Priya 80
4 3 Harini 74

In this example, we have arranged the rows of a data frame in ascending and descending order using the arrange() function.

  • To use the arrange() function. we have to load the ‘dplyr’ package as arrange() belongs to it.
  • The arrange() is the simplest way to arrange a data frame. It is because of the simplicity of it’s syntax.
  • By default, arrange() orders data in ascending order.
  • To order in descending we have to use the desc() function inside the arrange() function.
  • The arrange() function will have 2 main parameters..,
    • data frame name
    • column name (will have desc() if descending order is needed)
  • Print the result at the end.

Conclusion

A data frame is a 2-dimensional array that stores data and displays it in the form of a table. a data frame can have different types of data. In R the data frame is given a row number implicitly.
The functions order() and arrange() are used to order the data in increasing or decreasing order.

  • order() by default will order the data in ascending order.
  • To order the data in descending order we can use the line “decreasing = TRUE” to arrange the data in decreasing order.
  • We can also use the ‘-‘ sign inside the order() function and before the data frame name and column name to reverse the ascending order.
  • The arrange() function is from the ‘dplyr’ package so it is essential to load it to use the arrange(). We usually load the packages in R using the library(package_name) function.
  • arrange() will, by default arrange in ascending order but we can specify desc() function before the column name to arrange in descending order.
  • As a rule of thumb, we use the data frame name and $ symbol to select the required column.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads