按任意指定顺序对R中的列名重新排序

时间:2011-12-01 23:13:39

标签: r sorting dataframe

  

可能重复:
  How to sort a dataframe by column(s) in R

这是数据集:

odervect <- c("xaf", "c3a", "c3b", "ka101","jk12", "cd101", "kl01v", "klm1")
odervect
[1] "xaf" "c3a"   "c3b"   "ka101" "jk12"  "cd101" "kl01v" "klm1"  

dfd <- data.frame(ka101 = 101:110,c3a = 1:10, kl01v = 301:310, xaf = 11:20,
    c3b = 41:50, cd101 = 61:70)


 dfd 

   ka101 c3a kl01v xaf c3b cd101
1    101   1   301  11  41    61
2    102   2   302  12  42    62
3    103   3   303  13  43    63
4    104   4   304  14  44    64
5    105   5   305  15  45    65
6    106   6   306  16  46    66
7    107   7   307  17  47    67
8    108   8   308  18  48    68
9    109   9   309  19  49    69
10   110  10   310  20  50    70

期望的输出:

 dfd1 <- data.frame(xaf = 11:20, c3a = 1:10, c3b = 41:50,ka101 = 101:110, cd101 = 61:70,
     ka101v = 301:310)
    dfd1 
        xaf c3a c3b ka101 cd101 ka101v
1   11   1  41   101    61    301
2   12   2  42   102    62    302
3   13   3  43   103    63    303
4   14   4  44   104    64    304
5   15   5  45   105    65    305
6   16   6  46   106    66    306
7   17   7  47   107    67    307
8   18   8  48   108    68    308
9   19   9  49   109    69    309
10  20  10  50   110    70    310

请注意,并非dfd中存在订单向量中的所有名称,但只需对匹配的名称进行排序。

1 个答案:

答案 0 :(得分:9)

这个怎么样?它首先使用%in%选择(仍然按顺序)odervect中与dfd中的列名对应的字符串:

cnames <- odervect[odervect %in% names(dfd)]
dfd[cnames]
   xaf c3a c3b ka101 cd101 kl01v
1   11   1  41   101    61   301
2   12   2  42   102    62   302
3   13   3  43   103    63   303
4   14   4  44   104    64   304
5   15   5  45   105    65   305
6   16   6  46   106    66   306
7   17   7  47   107    67   307
8   18   8  48   108    68   308
9   19   9  49   109    69   309
10  20  10  50   110    70   310