There are two methods you can use to sort a table in R:
Method 1: Use Base R
#sort table in ascending order my_table_sorted <- my_table[order(my_table)] #sort table in descending order my_table_sorted <- my_table[order(my_table, decreasing=TRUE)]
Method 2: Use dplyr
library(dplyr) #sort table in ascending order my_table_sorted<- my_table %>% as.data.frame() %>% arrange(Freq) #sort table in descending order my_table_sorted<- my_table %>% as.data.frame() %>% arrange(desc(Freq))
The following examples show how to use each method in practice with the following table in R:
#create vector
data <- c(3, 8, 8, 8, 7, 7, 5, 5, 5, 5, 9, 12, 15, 15)
#create table
my_table <- table(data)
#view table
my_table
data
3 5 7 8 9 12 15
1 4 2 3 1 1 2
Example 1: Sort Table Using Base R
We can use the following code to sort the values in the table in ascending order using the order() function from base R:
#sort table in ascending order
my_table_sorted <- my_table[order(my_table)]
#view sorted table
my_table_sorted
data
3 9 12 7 15 8 5
1 1 1 2 2 3 4
And we can use the argument decreasing=True in the order() function to sort the values in the table in descending order:
#sort table in descending order
my_table_sorted <- my_table[order(my_table, decreasing=TRUE)]
#view sorted table
my_table_sorted
data
5 8 7 15 3 9 12
4 3 2 2 1 1 1
Example 2: Sort Table Using dplyr
We can use the following code to sort the values in the table in ascending order using the arrange() function from the dplyr package:
library(dplyr)
#sort table in ascending order
my_table_sorted <- my_table %>% as.data.frame() %>% arrange(Freq)
#view sorted table
my_table_sorted
data Freq
1 3 1
2 9 1
3 12 1
4 7 2
5 15 2
6 8 3
7 5 4
And we can use the desc() function to sort the values in the table in descending order:
library(dplyr)
#sort table in descending order
my_table_sorted <- my_table %>% as.data.frame() %>% arrange(desc(Freq))
#view sorted table
my_table_sorted
data Freq
1 5 4
2 8 3
3 7 2
4 15 2
5 3 1
6 9 1
7 12 1
Note: You can find the complete documentation for the dplyr arrange() function here.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Create a Frequency Table by Group in R
How to Create a Two Way Table in R
How to Plot a Table in R