1

我有一个数据框,其中包含变量 Alpha 到 Zulu,但没有任何特定顺序(例如 Bravo、Yankee、Charlie 等)。我想按字母顺序排列 Delta 到 Whiskey(20 个 vars),其余的保持原样。

例如无序 DF colnames(操作前):Zulu, Bravo, Alpha, Delta, Kilo, Tango, .... Whiskey, Yankee, X-Ray

例如有序 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')) ]

4

1 回答 1

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

于 2013-07-11T18:39:38.397 回答