自然地按多列排序数据帧

时间:2019-01-04 05:28:43

标签: r sorting dataframe sql-order-by natural-sort

我有一个像这样的数据框:

mydf <- data.frame(A=paste(sample(LETTERS, 4), sample(1:20, 20), sep="-"),
        B=paste(sample(1:20, 20), sample(LETTERS, 4), sep="-"),
        C=sample(LETTERS, 20), D=sample(1:100, 20), value=rnorm(20))
> mydf
      A    B C  D       value
1   P-2 15-D F 99  1.46364510
2   N-1 10-O M 96 -0.23821853
3   V-5 19-K N  5  0.09029719
4  Y-15 13-H I 97 -0.59500333
5  P-10 12-D B 14 -0.66379935
6  N-13 20-O K 86  0.18863555
7  V-12  2-K Y 18  0.30263287
8  Y-20 16-H D 89  0.61308283
9   P-8  1-D S 78  1.15020150
10  N-4  3-O L 72 -0.50010804
11 V-11  9-K J 94 -0.84123257
12  Y-9  6-H U 43  1.27020654
13  P-6  7-D V  8  1.88239736
14  N-3 17-O O 40 -0.12517285
15  V-7 11-K A 53  1.30788389
16 Y-17  4-H C 44 -0.48888627
17 P-16  5-D Q 71 -0.08965281
18 N-19  8-O G 66  2.68713761
19 V-14 14-K R 88  0.02622117
20 Y-18 18-H T 80 -2.93330039

现在我知道如何根据多列对其进行排序,但不知道如何以自然的方式进行...

mydf2 <- mydf[order(mydf[,1], mydf[,2], mydf[,3], decreasing=FALSE),]
> mydf2
      A    B C  D       value
2   N-1 10-O M 96 -0.23821853
6  N-13 20-O K 86  0.18863555
18 N-19  8-O G 66  2.68713761
14  N-3 17-O O 40 -0.12517285
10  N-4  3-O L 72 -0.50010804
5  P-10 12-D B 14 -0.66379935
17 P-16  5-D Q 71 -0.08965281
1   P-2 15-D F 99  1.46364510
13  P-6  7-D V  8  1.88239736
9   P-8  1-D S 78  1.15020150
11 V-11  9-K J 94 -0.84123257
7  V-12  2-K Y 18  0.30263287
19 V-14 14-K R 88  0.02622117
3   V-5 19-K N  5  0.09029719
15  V-7 11-K A 53  1.30788389
4  Y-15 13-H I 97 -0.59500333
16 Y-17  4-H C 44 -0.48888627
20 Y-18 18-H T 80 -2.93330039
8  Y-20 16-H D 89  0.61308283
12  Y-9  6-H U 43  1.27020654

您在上面的示例中看到,当正确的自然顺序应为N-1N-13N-19N-3N-4时,是N-1N-3N-4N-13N-19。我该如何做,但要进行自然排序?

是否有mixedorderorder一样的功能,就像有mixedsortsort一样?

0 个答案:

没有答案