我建议不要专注于特定示例,而是使用现有工具,mixedsort
在 gtools 包中处理不规则宽度的字母和数字字符。
require(gtools)
vec <- paste0( replicate(40, {
paste( sample(LETTERS, 3, repl=TRUE),collapse="")}),
sample(1:400, 40, repl=TRUE) )
mixedsort(vec)
[1] "ABP256" "ATV361" "ATZ12" "BKL273" "BOY273" "BQJ242" "CQL129"
[8] "CXH313" "CXQ249" "DFU116" "FGI305" "HJK249" "ICN4" "IML75"
[15] "JDJ309" "JEB93" "JHF276" "JIY265" "JXK287" "KCQ282" "MAR161"
[22] "MGV185" "MHH72" "NDJ84" "NGZ84" "OIV207" "ORK31" "PSJ95"
[29] "QOC178" "QXL344" "QYK285" "RFO98" "ROC135" "TUL40" "UBT134"
[36] "UKP14" "VQL372" "YLG393" "ZLD394" "ZSG180"
如果mixedsort
不存在,人类将需要发明它。这并不完全会产生相同的结果,但它可能会照亮前进的道路:
vec[ order( gsub("[[:digit:]]", "", vec), gsub("[[:alpha:]]", "", vec) )]
[1] "ABP256" "ATV361" "ATZ12" "BKL273" "BOY273" "BQJ242" "CQL129"
[8] "CXH313" "CXQ249" "DFU116" "FGI305" "HJK249" "ICN4" "IML75"
[15] "JDJ309" "JEB93" "JHF276" "JIY265" "JXK287" "KCQ282" "MAR161"
[22] "MGV185" "MHH72" "NDJ84" "NGZ84" "OIV207" "ORK31" "PSJ95"
[29] "QOC178" "QXL344" "QYK285" "RFO98" "ROC135" "TUL40" "UBT134"
[36] "UKP14" "VQL372" "YLG393" "ZLD394" "ZSG180"
它将所有字母字符折叠在数字之前,并将order
“a12b”放在“a99z”之前。