Sort data frame by two columns (with condition)
本问题已经有最佳答案,请猛点这里访问。
我在R中有以下数据帧:
1 2 3 4 5 6 7 8 9 | DataTable <- data.frame( Name = c("Nelle","Alex","Thomas","Jeff","Rodger","Michi"), Age = c(17, 18, 18, 16, 16, 16), Grade = c(1,5,3,2,2,4) ) Name Age Grade 1 Nelle 17 1 2 Alex 18 5 3 Thomas 18 3 4 Jeff 16 2 5 Rodger 16 2 6 Michi 16 4 |
现在,Ill将按其
1 2 3 4 5 6 7 8 9 | DataTable_sort_age <- DataTable[with(DataTable, order(DataTable[,2])),] Name Age Grade 4 Jeff 16 2 5 Rodger 16 2 6 Michi 16 4 1 Nelle 17 1 2 Alex 18 5 3 Thomas 18 3 |
号
在
1 2 3 4 5 6 7 | Name Age Grade 1 Jeff 16 2 2 Michi 16 2 3 Rodger 16 4 4 Nelle 17 1 5 Alex 18 5 6 Thomas 18 3 |
希望您能帮我按字母顺序对数据帧进行排序。
根据@stezzo的评论更新答案
只需在
1 2 3 4 5 6 7 8 9 | 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 |
记住,传递参数的顺序很重要。它将首先对数据表数据帧w.r.t第二列进行排序,如果出现绑定,它将考虑第二个参数,即第一列。
除了@ronak shah答案,您还可以使用
1 | arrange(DataTable,Age,Name) |
号
给予
1 2 3 4 5 6 7 8 | 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 |
这里,它首先按