How to perform natural (lexicographic) sorting in R?
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"
Natural sorting is available in the stringr
/stringi
packages with the functions str_sort()
/stri_sort()
. Switching between alphanumeric and natural sorting is controlled by the 'numeric' argument.
library(stringr)
# library(stringi)
str_sort(seq.names, numeric = TRUE)
# stri_sort(seq.names, numeric = TRUE)
[1] "1a" "1b" "abc1" "abc01" "abc2" "abc4" "abc21" "abc201"
The companion function str_order()
/ stri_order()
returns the indices to arrange the vector in (by default) ascending order:
str_order(seq.names, numeric = TRUE)
# stri_order(seq.names, numeric = TRUE)
[1] 8 7 3 4 2 5 1 6
seq.names[str_order(seq.names, numeric = TRUE)]
[1] "1a" "1b" "abc1" "abc01" "abc2" "abc4" "abc21" "abc201"