Sort data frame by two columns (with condition) [duplicate]

百般思念 提交于 2019-11-29 15:54:53

As per @Stezzo 's comment updating the answer

Just add, DataTable[, 1] in the order function

DataTable[order(DataTable[,2], DataTable[, 1]),]

#    Name Age Grade
# 4   Jeff  16     2
# 6  Michi  16     4
# 5 Rodger  16     2
# 1  Nelle  17     1
# 2   Alex  18     5
# 3 Thomas  18     3

Remember, the order in which parameters are passed matters. It would first sort the DataTable dataframe w.r.t 2nd column and in case of a tie it would consider the second parameter which is the first column.

Dhawal Kapil

in addition to @Ronak Shah answer you can also use arrange of dplyr. It looks a bit simpler to me.

arrange(DataTable,Age,Name)

gives

    Name Age Grade
1   Alex  16     3
2   Jeff  16     2
3  Michi  16     4
4 Rodger  16     2
5  Nelle  17     1
6   Alex  18     5
7 Thomas  18     4

Here, it first sorts by Age then Name and you can add more variables so on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!