To sort the column of dataframe in R we use order() function, with the help of order() function we can sort the column in descending order or ascending order. Let’s see how to
- Sort the column of dataframe in R in ascending order
- Sort the column of dataframe in R in descending order
Let’s first create the dataframe.
df1= data.frame(Name=c('James','Paul','Richards','Marico','Samantha','Ravi','Raghu','Richards','George','Ema','Samantha','Catherine'), State=c('Alaska','California','Texas','North Carolina','California','Texas','Alaska','Texas','North Carolina','Alaska','California','Texas'), Sales=c(14,24,24,32,13,7,9,41,18,16,28,14)) df1
So the resultant dataframe will be
Sort the column of dataframe in R by ascending order:
Sorting the column is done with the help of order function. Default is ascending order
## Sort the column by ascending df2 <- df1[order(df1$Sales),] df2
So the sorted dataframe will be
Sort the column of dataframe in R by descending order:
Sorting the column is done with the help of order function, specifying minus symbol orders the column in descending order as shown
## Sort the column by descending df2 <- df1[order(-df1$Sales),] df2
So the sorted dataframe will be
Sort by multiple column of dataframe in R:
In below example lets first sort by column “state” in ascending order and then sort by “sales” in descending order
## Sort by multiple column df2 <- df1[order(df1$State,-df1$Sales),] df2
So the sorted dataframe will be