根据第二个数据帧中的信息对数据帧的列进行排序(在R中)

时间:2014-08-14 10:34:59

标签: r sorting

我有一个带有变量名称的数据框,以及我希望它们所在的顺序的1:p索引。 我有第二个数据框,这些变量的顺序都搞砸了。如何从第一个信息中获取信息来订购第二个列?

1> key = data.frame(index = 1:6,vars = paste("V",1:6,sep=""))
1> key
  index vars
1     1   V1
2     2   V2
3     3   V3
4     4   V4
5     5   V5
6     6   V6
1> set.seed(42)
1> data = data.frame(matrix(rnorm(60),10))
1> colnames(data) = sample(key$vars)
1> data
            V3         V6         V5          V2         V4          V1
1   1.37095845  1.3048697 -0.3066386  0.45545012  0.2059986  0.32192527
2  -0.56469817  2.2866454 -1.7813084  0.70483734 -0.3610573 -0.78383894
3   0.36312841 -1.3888607 -0.1719174  1.03510352  0.7581632  1.57572752
4   0.63286260 -0.2787888  1.2146747 -0.60892638 -0.7267048  0.64289931
5   0.40426832 -0.1333213  1.8951935  0.50495512 -1.3682810  0.08976065
6  -0.10612452  0.6359504 -0.4304691 -1.71700868  0.4328180  0.27655075
7   1.51152200 -0.2842529 -0.2572694 -0.78445901 -0.8113932  0.67928882
8  -0.09465904 -2.6564554 -1.7631631 -0.85090759  1.4441013  0.08983289
9   2.01842371 -2.4404669  0.4600974 -2.41420765 -0.4314462 -2.99309008
10 -0.06271410  1.3201133 -0.6399949  0.03612261  0.6556479  0.28488295

1 个答案:

答案 0 :(得分:2)

data[as.character(key$vars)]

会做到这一点。

#             V1          V2          V3         V4         V5         V6
# 1   0.32192527  0.45545012  1.37095845  0.2059986 -0.3066386  1.3048697
# 2  -0.78383894  0.70483734 -0.56469817 -0.3610573 -1.7813084  2.2866454
# 3   1.57572752  1.03510352  0.36312841  0.7581632 -0.1719174 -1.3888607
# 4   0.64289931 -0.60892638  0.63286260 -0.7267048  1.2146747 -0.2787888
# 5   0.08976065  0.50495512  0.40426832 -1.3682810  1.8951935 -0.1333213
# 6   0.27655075 -1.71700868 -0.10612452  0.4328180 -0.4304691  0.6359504
# 7   0.67928882 -0.78445901  1.51152200 -0.8113932 -0.2572694 -0.2842529
# 8   0.08983289 -0.85090759 -0.09465904  1.4441013 -1.7631631 -2.6564554
# 9  -2.99309008 -2.41420765  2.01842371 -0.4314462  0.4600974 -2.4404669
# 10  0.28488295  0.03612261 -0.06271410  0.6556479 -0.6399949  1.3201133