根据某些字符排序字符串

时间:2016-05-10 08:31:08

标签: r string sorting

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

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]

但我想可能会有更简单的事情

1 个答案:

答案 0 :(得分:3)

通过gtools

可以轻松实现此目的
gtools::mixedsort(str)
#[1] "N1someotherstring"  "N2someotherstring"  "N5someotherstring"  "N10someotherstring" "N11someotherstring" "N20someotherstring"