按两列对数据框进行排序(有条件) [英] Sort data frame by two columns (with condition)
问题描述
我在R中具有以下数据框:
I have the following data frame in R:
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
现在,病态患者将按其Age
列对该数据帧进行排序.到目前为止没有问题:
Now ill will sort this data frame by its Age
column. No problem so far:
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
Name
列中的年龄相同的人更多,应该按字母顺序对其进行排序.如果满足相同年龄的多个人的条件为真,则数据框应按Name
按字母顺序排序.输出应如下所示:
There are more persons in the Name
columns that have the same age and they should be sorted alphabetically. If the condition, that more than one person is at the same age, is true the data frame should be sorted alphabetically by Name
. The output should look like this:
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
希望您可以按字母顺序对数据框进行排序.
Hope you can help me by sorting the data frame alphabetically.
推荐答案
按照@Stezzo的评论更新答案
As per @Stezzo 's comment updating the answer
只需在order
函数中添加DataTable[, 1]
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第二列的DataTable数据帧进行排序,如果出现平局,它将考虑第二个参数即第一列.
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.
这篇关于按两列对数据框进行排序(有条件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!