对R中的列名重新排序

可能重复:
如何按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中存在顺序矢量中的所有名称,但只需对相匹配的名称进行排序。


这个怎么样? 它首先使用%in%来选择(仍按顺序) odervect中对应于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
链接地址: http://www.djcxy.com/p/70845.html

上一篇: Reorder column names in R

下一篇: Reordering and reshaping columns in R