How to Reorder Rows of DataFrame in R

You can use the arrange() function from the dplyr package to reorder rows of a data frame in R. The arrange() function can sort rows in ascending or descending order based on one or more columns.

Syntax

library(dplyr)

df %>% arrange(name)

Install the dplyr package to use the arrange() function.

Or you can sort it by value in descending order like this.

library(dplyr)

df %>% arrange(desc(value))

You can also use a vector with a specific order to reorder the rows according to that order. For example, if you have a vector called target that contains the desired order of names, use the below syntax.

library(dplyr)

df %>% arrange(factor(name, levels = target))

Example

library(dplyr)

df <- data.frame(
  A = c(1, 2, 3),
  B = c("a", "b", "c"),
  C = c(TRUE, FALSE, TRUE),
  D = c(0.1, 0.2, 0.3)
)

df

cat("After reordering the 'C' row of a data frame", "\n")

df_reorder <- df %>% arrange(C)

df_reorder

Output


   A  B   C     D
1  1  a  TRUE  0.1
2  2  b  FALSE 0.2
3  3  c  TRUE  0.3

After reordering the 'C' column values of a data frame

   A  B   C     D
1  2  b  FALSE 0.2
2  1  a  TRUE  0.1
3  3  c  TRUE  0.3

In this example, we loaded the dplyr package and created a sample DataFrame df.

In the next step, we used the arrange() function to reorder the rows by age in ascending order.

Finally, we printed the reordered DataFrame.

How to reorder multiple rows of a data frame in R

To reorder multiple rows of a data frame in R, you can use the arrange() function from the dplyr package. This function can sort rows based on one or more columns in ascending or descending order.

Syntax

library(dplyr)

df %>% arrange(col1, col2)

Or you can sort it by gender and then by age in descending order like this:

library(dplyr)

df %>% arrange(desc(col1), desc(col2))

Example

library(dplyr)

df <- data.frame(
  A = c(1, 2, 3),
  B = c("a", "b", "c"),
  C = c(TRUE, FALSE, TRUE),
  D = c(0.1, 0.2, 0.3)
)

df

cat("After reordering the multiple rows of a data frame", "\n")

df_reorder <- df %>% arrange(desc(A), D)

df_reorder

Output


   A  B   C    D
1  1  a  TRUE  0.1
2  2  b  FALSE 0.2
3  3  c  TRUE  0.3

After reordering the multiple rows of a data frame

   A  B  C     D
1  3  c TRUE  0.3
2  2  b FALSE 0.2
3  1  a TRUE  0.1

In this example, we used the arrange() function to sort by A in descending order and D in ascending order.

The desc() function suggests that the height should be sorted in descending order.

That’s it.

Leave a Comment