Sort data frame by two columns (with condition)

This question already has an answer here:

  • How to sort a dataframe by multiple column(s)? 16 answers

  • 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 wrt 2nd column and in case of a tie it would consider the second parameter which is the first column.


    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.

    链接地址: http://www.djcxy.com/p/70840.html

    上一篇: R中的函数重新排序和排序值

    下一篇: 按两列对数据框排序(带条件)