You can use the following two methods to sort a data frame in R by using the row.names attribute:
Method 1: Sort Using Character row.names
df[order(row.names(df)), ]
Method 2: Sort Using Numeric row.names
df[order(as.numeric(row.names(df))), ]
The following examples shows how to use each method in practice.
Example 1: Sort Data Frame Using Character row.names
Suppose we have the following data frame in R:
#create data frame
df <- data.frame(position=c('G', 'G', 'F', 'F', 'C'),
points=c(99, 90, 86, 88, 95),
assists=c(33, 28, 31, 39, 34),
rebounds=c(30, 28, 24, 24, 28))
#set row names of data frame
row.names(df) <- c('A', 'C', 'E', 'D', 'B')
#view data frame
df
position points assists rebounds
A G 99 33 30
C G 90 28 28
E F 86 31 24
D F 88 39 24
B C 95 34 28
We can use the following syntax to sort the rows of the data frame alphabetically using the row.names attribute:
#sort rows alphabetically using row.names
df[order(row.names(df)), ]
position points assists rebounds
A G 99 33 30
B C 95 34 28
C G 90 28 28
D F 88 39 24
E F 86 31 24
The rows are sorted from A to Z based on the row name value.
You can also use the decreasing=TRUE argument to sort from Z to A:
#sort rows from Z to A using row.names
df[order(row.names(df), decreasing=TRUE), ]
position points assists rebounds
E F 86 31 24
D F 88 39 24
C G 90 28 28
B C 95 34 28
A G 99 33 30
Example 2: Sort Data Frame Using Numeric row.names
Suppose we have the following data frame in R:
#create data frame
df <- data.frame(position=c('G', 'G', 'F', 'F', 'C'),
points=c(99, 90, 86, 88, 95),
assists=c(33, 28, 31, 39, 34),
rebounds=c(30, 28, 24, 24, 28))
#set row names of data frame
row.names(df) <- c(1, 100, 4, 12, 19)
#view data frame
df
position points assists rebounds
1 G 99 33 30
100 G 90 28 28
4 F 86 31 24
12 F 88 39 24
19 C 95 34 28
#sort by row names from smallest to largest
df[order(as.numeric(row.names(df))), ]
position points assists rebounds
1 G 99 33 30
4 F 86 31 24
12 F 88 39 24
19 C 95 34 28
100 G 90 28 28
We could also use decreasing=TRUE to sort from largest to smallest:
#sort by row names from largest to smallest
df[order(as.numeric(row.names(df)), decreasing=TRUE), ]
position points assists rebounds
100 G 90 28 28
19 C 95 34 28
12 F 88 39 24
4 F 86 31 24
1 G 99 33 30
Additional Resources
The following tutorials explain how to perform other common operations in R: