6.9 C
London
Thursday, December 19, 2024
HomeStatistics TutorialRHow to Sort by Multiple Columns in R (With Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories