ClementWalter
ClementWalter

Reputation: 5324

order strings according to some characters

I have a vector of strings, each of those has a number inside and I like to sort this vector according to this number.

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"

while I'd like to have

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

I have thought of using something like:

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

but I guess there might be something simpler

Upvotes: 0

Views: 27

Answers (1)

Sotos
Sotos

Reputation: 51592

There is an easy way to do this via gtools package,

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

Upvotes: 3

Related Questions