How to perform natural (lexicographic) sorting in R?

cbare picture cbare · May 6, 2010 · Viewed 9.7k times · Source

Is there a natural sort for R?

Say I had a character vector like so:

seq.names <- c('abc21', 'abc2', 'abc1', 'abc01', 'abc4', 'abc201', '1b', '1a')

I'd like to sort it aphanumerically, so I get back this:

c('1a', '1b', 'abc1', 'abc01', 'abc2', 'abc4', 'abc21', 'abc201')

Does this exist somewhere, or should I start coding?

Answer

Nicholas Riley picture Nicholas Riley · May 6, 2010

I don't think "alphanumeric sort" means what you think it means.

In any case, looks like you want mixedsort, part of gtools.

> install.packages('gtools')
[...]
> require('gtools')
Loading required package: gtools
> n
[1] "abc21"  "abc2"   "abc1"   "abc01"  "abc4"   "abc201" "1b"     "1a"    
> mixedsort(n)
[1] "1a"     "1b"     "abc1"   "abc01"  "abc2"   "abc4"   "abc21"  "abc201"