我有一个包含以下列名的数据框:
[1] "416362" "417510" "402634" "406503" "417510" "402634" "402634" "402634" "402634" "402634" "406801" "416631" "407508" "413513" "406801" "416362" "416631" "406603" "407508" "416631" "406603" "406531" "402634" "402634" "402634"
[26] "406503" "413513" "416631" "416631" "406531"
请注意,这些数字是混乱的,并且 重复
我想重新组织列,以便它们遵循以下顺序:
[1] "402634" "406503" "406531" "406603" "406801" "407508" "413513" "416362" "416631" "417510"
所以我希望所有列号都在混乱的矩阵中有“402634”。然后,在矢量中,在混乱矩阵中具有“406503”的所有列号都说“x”。
然后,我想df[,x]
重新组织我的数据框df
。
谢谢!
答案 0 :(得分:1)
在列名称上使用order
命令:
currentNames = c("416362","417510","402634","406503","417510","402634","402634","402634","402634","402634",
"406801","416631","407508","413513","406801","416362","416631","406603","407508","416631",
"406603","406531","402634","402634","402634","406503","413513","416631","416631","406531")
df = data.frame(matrix(nrow=3,ncol=length(currentNames)))
colnames(df) = currentNames
df[1:nrow(df),1:ncol(df)] = runif(nrow(df)*ncol(df))
df = df[,order(colnames(df),decreasing=F)]