15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Sort a Data Frame by Column in R (With Examples)

How to Sort a Data Frame by Column 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...

The easiest way to sort a data frame by a column in R is to use the order() function:

#sort ascending
df[order(df$var1), ]

#sort descending
df[order(-df$var1), ]

This tutorial provides several examples of how to use this function in practice with the following data frame:

#create data frame
df frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, 7, 8, 3, 2),
                 var3=letters[1:5])

#view data frame
df

  var1 var2 var3
1    1    7    a
2    3    7    b
3    3    8    c
4    4    3    d
5    5    2    e

Example 1: Sort by One Column

The following code shows how to sort the data frame by the var1 column, both in an ascending and descending manner:

#sort by var1 ascending
df[order(df$var1), ]

  var1 var2 var3
1    1    7    a
2    3    7    b
3    3    8    c
4    4    3    d
5    5    2    e

#sort by var1 descending
df[order(-df$var1), ]

  var1 var2 var3
5    5    2    e
4    4    3    d
2    3    7    b
3    3    8    c
1    1    7    a

Note that we can also sort by a character vector alphabetically:

#sort by var3 ascending
df[order(df$var3), ]

  var1 var2 var3
1    1    7    a
2    3    7    b
3    3    8    c
4    4    3    d
5    5    2    e

Example 2: Sort by Multiple Columns

The following code shows how to sort the data frame by multiple columns:

#sort by var2 ascending, then var1 ascending
df[order(df$var2, df$var1), ]

  var1 var2 var3
5    5    2    e
4    4    3    d
1    1    7    a
2    3    7    b
3    3    8    c

#sort by var2 ascending, then var1 descending
df[order(df$var2, -df$var1), ]

  var1 var2 var3
5    5    2    e
4    4    3    d
2    3    7    b
1    1    7    a
3    3    8    c

Additional Resources

How to Add a Column to a Data Frame in R
How to Sort a Data Frame by Date in R
How to Convert Character to Numeric 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