How to Sort Values Alphabetically in R


You can use the following functions to sort values alphabetically in R:

#sort values in vector alphabetically
sort(x)

#sort data frame column alphabetically
df[order(df$var1), ]

#sort data frame by multiple columns alphabetically
df[with(df, order(var1, var2)), ]

The following examples show how to use each of these functions in practice.

Example 1: Sort a Vector Alphabetically

The following code shows how to sort a vector alphabetically in R:

#define vector
x <- c('A', 'F', 'C', 'D', 'B', 'E')

#sort values in vector alphabetically
sort(x)

[1] "A" "B" "C" "D" "E" "F"

Example 2: Sort Data Frame Column Alphabetically

The following code shows how to sort a data frame alphabetically based on a specific column:

#define data frame
df <- data.frame(player=c('A', 'F', 'C', 'D', 'B', 'E'),
                 points=c(14, 19, 22, 29, 31, 16))

#view data frame
df

  player points
1      A     14
2      F     19
3      C     22
4      D     29
5      B     31
6      E     16

#sort data frame alphabetically based on player column
df[order(df$player),]

  player points
1      A     14
5      B     31
3      C     22
4      D     29
6      E     16
2      F     19

Example 3: Sort Multiple Columns Alphabetically

The following code shows how to sort a data frame alphabetically based on multiple columns:

#define data frame
df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'B'),
                 player=c('A', 'F', 'C', 'D', 'B', 'E'),
                 points=c(14, 19, 22, 29, 31, 16))

#view data frame
df

  team player points
1    A      A     14
2    A      F     19
3    A      C     22
4    B      D     29
5    B      B     31
6    B      E     16

#sort data frame alphabetically by team, then by player
df[with(df, order(team, player)), ]

  team player points
1    A      A     14
3    A      C     22
2    A      F     19
5    B      B     31
4    B      D     29
6    B      E     16

Additional Resources

How to Sort a Data Frame by Column in R
How to Sort a Data Frame by Date in R
How to Drop Columns from Data Frame in R

Leave a Reply

Your email address will not be published.