How to Sort a Data Frame by Column in R (With Examples)

In R, data frames can be sorted by column using the order() and arrange() functions. The order() function sorts the data frame by the specified column in either ascending or descending order, while the arrange() function sorts using dplyr syntax. Both of these functions are demonstrated in this article with examples of their use.


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

x