user3001378
user3001378

Reputation: 316

Sort in R with multiple criteria (alphanumeric)

l <-  c("BC321" , "BC320", "BC100" , "DA124" ,"DA174" ,"DA224", "DA33",  "DA98" )
require('gtools')
mixedsort(l)
"BC100" "BC320" "BC321" "DA33"  "DA98"  "DA124" "DA174" "DA224"

But I want "DA33" "DA98" "DA124" "DA174" "DA224" "BC100" "BC320" "BC321"

Really appreciate any help. Thank you

Upvotes: 1

Views: 198

Answers (1)

Arun
Arun

Reputation: 118799

Here's one way:

x <- strsplit(l, "(?<=[A-Z])(?=[0-9])", perl=TRUE) ##
v1 = sapply(x, `[[`, 1L)
v2 = as.integer(sapply(x, `[[`, 2L))
l[order(-xtfrm(v1), v2)]
# [1] "DA33"  "DA98"  "DA124" "DA174" "DA224" "BC100" "BC320" "BC321"

Check this post by Josh O'Brien for the magic happening with strsplit (marked with ##).

Upvotes: 2

Related Questions