Reorder column names in R by arbitrary specified order
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How to sort a dataframe by column(s) in R
号
以下是数据集:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |
期望输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 |
号
请注意,并非顺序向量中的所有名称都存在于
这个怎么样?它首先使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |