R:在数据框中订购特定的变量

时间:2013-07-11 17:33:56

标签: r

我有一个数据框,其中包含变量Alpha thru Zulu,但没有任何特定顺序(例如Bravo,Yankee,Charlie等)。我想按字母顺序命令三角洲通过威士忌(20个变种),剩下的就是它们。

e.g。无序的DF colnames(操作前):Zulu, Bravo, Alpha, Delta, Kilo, Tango, .... Whiskey, Yankee, X-Ray

e.g。订购的DF colnames(操作后):Zulu, Bravo, Alpha, #Start ordered section# Delta, Echo, Fox, Golf, .... Whiskey, #End ordered section# Yankee, X-Ray

我认为我接近使用order命令,但我遗漏了一些东西......

DF <- DF[ , order( which(names(DF) == 'Delta') : which(names(mitch) == 'Whiskey')) ]

1 个答案:

答案 0 :(得分:1)

这对我有用:

# Create list of variables to sort
names.DF <- names(DF)

# Find just the variables between the 4th variable ('Delta') and the 23rd variable ('Whiskey') 
ord <- names.DF %in% sort(names.DF)[(which(names.DF=='Delta')):(which(names.DF=='Whiskey'))]

# Replace just the desired variables with the properly sorted variables
names.DF[ord] <- sort(names.DF[ord])

# Use the sorted list to sort the variables in the dataframe
DF <- DF[,names.DF]

此解决方案将根据需要对变量进行排序。它还可以处理Alpha,Bravo,Charlie,X-ray,Yankee和Zulu与您想要的变量混合的情况,而不仅仅是两端。例如,

Zulu, Alpha, X-ray, Echo, Whiskey, Delta, Golf, Bravo, Charlie, Yankee

变为

Zulu, Alpha, X-ray, Delta, Echo, Golf, Whiskey, Bravo, Charlie, Yankee

Echo, Zulu, Whiskey, Delta, Alpha, X-ray, Bravo, Charlie, Golf, Yankee

变为

Delta, Zulu, Echo, Golf, Alpha, X-ray, Bravo, Charlie, Whiskey, Yankee