+2 votes
in Programming Languages by (60.0k points)
I want to sort the records of dataframe by 2/3 columns. How can I sort it by its multiple columns?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

You can use the order() method to sort a dataframe. You need to mention columns as parameters of this method.

Here is an example:

> df1 = data.frame(a=c(12,21,13,17,18,14,10), b=c(23,12,54,76,34,9,78), c=c(887,343,123,1445,654,234,871))
> df1
   a  b    c
1 12 23  887
2 21 12  343
3 13 54  123
4 17 76 1445
5 18 34  654
6 14  9  234
7 10 78  871

Sort by multiple columns in ascending order.

> df1[order(df1$a, df1$b),]
   a  b    c
7 10 78  871
1 12 23  887
3 13 54  123
6 14  9  234
4 17 76 1445
5 18 34  654
2 21 12  343

Sort by multiple columns, "a" descending and then "b" ascending.

> df1[order(-df1$a, df1$b),]
   a  b    c
2 21 12  343
5 18 34  654
4 17 76 1445
6 14  9  234
3 13 54  123
1 12 23  887
7 10 78  871


...