繁体   English   中英

根据某些字符排序字符串

[英]order strings according to some characters

我有一个字符串向量,每个字符串里面都有一个数字,我想根据这个数字对向量进行排序。

MWE:

> str = paste0('N', sample(c(1,2,5,10,11,20), 6, replace = FALSE), 'someotherstring')
> str
[1] "N11someotherstring" "N5someotherstring"  "N2someotherstring"  "N20someotherstring" "N10someotherstring" "N1someotherstring" 
> sort(str)
[1] "N10someotherstring" "N11someotherstring" "N1someotherstring"  "N20someotherstring" "N2someotherstring"  "N5someotherstring"

而我想拥有

[1] "N1someotherstring"  "N2someotherstring"  "N5someotherstring"  "N10someotherstring" "N11someotherstring" "N20someotherstring"

我曾想过使用类似的东西:

num = sapply(strsplit(str, split = NULL), function(s) {
  as.numeric(paste0(head(s, -15)[-1], collapse = ""))
})
str = str[sort(num, index.return=TRUE)$ix]

但我想可能会更简单

有一个简单的方法可以通过gtools软件包来实现,

gtools::mixedsort(str)
#[1] "N1someotherstring"  "N2someotherstring"  "N5someotherstring"  "N10someotherstring" "N11someotherstring" "N20someotherstring"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM