How to Sort by Multiple Columns in R (With Examples)


You can use one of the following methods to sort a data frame by multiple columns in R:

Method 1: Use Base R

df[order(-df$column1, df$column2), ]

Method 2: Use dplyr

library(dplyr)

df %>%
  arrange(desc(column1), column2)

The following examples show how to use each method in practice with the following data frame:

#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
                 points=c(90, 90, 93, 91, 91, 99, 85),
                 assists=c(33, 28, 31, 39, 34, 40, 44))

#view data frame
df

  team points assists
1    A     90      33
2    B     90      28
3    C     93      31
4    D     91      39
5    E     91      34
6    F     99      40
7    G     85      44

Method 1: Use Base R

The following code shows how to sort the data frame in base R by points descending (largest to smallest), then by assists ascending:

#sort by points descending, then by assists ascending
df[order(-df$points, df$assists), ]

  team points assists
6    F     99      40
3    C     93      31
5    E     91      34
4    D     91      39
2    B     90      28
1    A     90      33
7    G     85      44

Notice that the rows of the data frame are ordered by points from largest to smallest, then by assists from smallest to largest.

Method 2: Use dplyr

The following code shows how to use functions from the dplyr package to sort the data frame by points descending (largest to smallest), then by assists ascending:

library(dplyr)

df %>%
  arrange(desc(points), assists)

  team points assists
1    F     99      40
2    C     93      31
3    E     91      34
4    D     91      39
5    B     90      28
6    A     90      33
7    G     85      44

Once again, the rows of the data frame are ordered by points from largest to smallest, then by assists from smallest to largest.

Note: You can find the complete documentation for the arrange() function here.

Additional Resources

The following tutorials explain how to perform other common sorting operations in R:

How to Sort Values Alphabetically in R
How to Sort a Data Frame by Date in R

Leave a Reply

Your email address will not be published.