Reorder column names in R
Possible Duplicate:
How to sort a dataframe by column(s) in R
Here is the dataset:
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
Desired output:
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
Please note that not all names in order vector are present in dfd
, however only need to sort the matching ones.
How about this? It first uses %in%
to select (still in order) the strings in odervect
that correspond to column names present in 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/70846.html
上一篇: 如何按字母顺序排序数据帧?
下一篇: 对R中的列名重新排序