R:行的嵌套排序

时间:2018-01-04 04:46:38

标签: r

是否可以轻松地对数据框或矩阵的两列中的行元素进行嵌套排序?

我有以下数据集:

structure(list(Group = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 
1L, 2L, 1L, 2L, 1L), .Label = c("A", "B"), class = "factor"), 
    Education = structure(c(5L, 3L, 5L, 6L, 6L, 5L, 2L, 2L, 6L, 
    5L, 3L, 6L), .Label = c("Below NVQ Level 2", "No qualification", 
    "NVQ Level 2", "NVQ Level 4 and above", "NVQ Level3", "Other qualification"
    ), class = "factor"), Full.Time = c(26, 22, 27, 18, 27, 26, 
    9, 9, 27, 27, 22, 18), PT.16.hours = c(21, 21, 24, 18, 14, 
    21, 12, 12, 14, 24, 21, 18), PT.16.hours.1 = c(25, 25, 11, 
    13, 16, 25, 5, 5, 16, 11, 25, 13)), .Names = c("Group", "Education", 
"Full.Time", "PT.16.hours", "PT.16.hours.1"), row.names = c("8", 
"9", "2", "5", "11", "8.1", "6", "6.1", "11.1", "2.1", "9.1", 
"5.1"), class = "data.frame")

当读入R时如下:

 DD
     Group           Education Full.Time PT.16.hours PT.16.hours.1
8        B          NVQ Level3        26          21            25
9        B         NVQ Level 2        22          21            25
2        A          NVQ Level3        27          24            11
5        A Other qualification        18          18            13
11       B Other qualification        27          14            16
8.1      B          NVQ Level3        26          21            25
6        A    No qualification         9          12             5
6.1      A    No qualification         9          12             5
11.1     B Other qualification        27          14            16
2.1      A          NVQ Level3        27          24            11
9.1      B         NVQ Level 2        22          21            25
5.1      A Other qualification        18          18            13

我想订购这样的行,以便A和B按顺序排列(首先是A&A;)然后是B&A,并且每个A都在A中和B,我希望以嵌套的方式对教育进行排序(排序)。其他列应保持相同的关系。我觉得这是一个简单的问题,但是如何有效地做到这一点?

提前致谢。

1 个答案:

答案 0 :(得分:1)

在基础R中,很容易用

实现
df[ order( df$Group, df$Education ), ]

     Group           Education Full.Time PT.16.hours PT.16.hours.1
6        A    No qualification         9          12             5
6.1      A    No qualification         9          12             5
2        A          NVQ Level3        27          24            11
2.1      A          NVQ Level3        27          24            11
5        A Other qualification        18          18            13
5.1      A Other qualification        18          18            13
9        B         NVQ Level 2        22          21            25
9.1      B         NVQ Level 2        22          21            25
8        B          NVQ Level3        26          21            25
8.1      B          NVQ Level3        26          21            25
11       B Other qualification        27          14            16
11.1     B Other qualification        27          14            16