2013-07-08 57 views
20

我有一個字符數組如何對元素包含R中的字母和數字的字符向量進行排序?

cf <- c("V440","V457","V116","V327","V446","V108", 
     "V155","V217","V120","V51","V477") 

我想它降序排列,讓我有一個這樣的輸出:

V51 
V108 
V116 
V120 
V155 
V217 
V327 
V440 
V446 
V457 
V477 

我已經試過sort.list()這樣

cf[sort.list(cf)] 

並得到了這個答案:

[1] "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477" "V51" 

也試過order()並得到了相同的結果。

有人可以幫我請

回答

31

嘗試從 「gtools」 包mixedsort

> # install.packages("gtools") ## Uncomment if not already installed 
> library(gtools) 
> mixedsort(cf) 
[1] "V51" "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477" 

如果你不想使用mixedsort(不知道爲什麼人們不會) ,如果你的矢量有一個相當一致的模式(例如字母后跟數字),你也可以嘗試這樣的事情。 (注:相對未經測試。)

newvec <- c("V440", "V457", "V116", "V327", "V446", "V108", "V155", 
      "V217", "V120", "V51", "V477", "B22", "A10", "Z01") 

newvec[order(gsub("([A-Z]+)([0-9]+)", "\\1", newvec), 
      as.numeric(gsub("([A-Z]+)([0-9]+)", "\\2", newvec)))] 
# [1] "A10" "B22" "V51" "V108" "V116" "V120" "V155" "V217" "V327" "V440" 
# [11] "V446" "V457" "V477" "Z01" 
3

只要颳去前面的 「V」 字建立一個分類矢量。不需要額外的花式工具。

vals <- as.numeric(gsub("V","", cf)) 
cf[order(vals)] 

[1] "V51" "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" 
[10] "V457" "V477" 
3

R按字母順序正確命令字符串,這就是爲什麼你會得到該結果。

除了@Ananda很好的答案,如果你想使用基礎R可以用strsplit從每個字符串中刪除了「V」,然後使用as.numeric到字符串轉換爲整數:

vals <- as.numeric(sapply(cf, FUN=function(x){strsplit(x, "V")[[1]][2]})) 

現在,您可以使用vals

cf[order(vals)] 
1

下面是利用namessort基本方法(阿難的是非常漂亮的),您的字符串進行排序:

cf <- c("V440","V457","V116","V327","V446","V108", 
     "V155","V217","V120","V51","V477") 

cf2 <- as.numeric(gsub("[^[:digit:]]", "", cf)) 
names(cf2) <- seq_along(cf2) 
cf[as.numeric(names(sort(cf2)))] 

## > cf[as.numeric(names(sort(cf2)))] 
## [1] "V51" "V108" "V116" "V120" "V155" "V217" "V327" 
## [8] "V440" "V446" "V457" "V477" 
25

很多正確的答案在這裏,這是另一種方式,只是爲了好玩。

cf[order(nchar(cf), cf)] 
# [1] "V51" "V108" "V116" "V120" "V155" "V217" "V327" "V440" "V446" "V457" "V477" 
相關問題