28

R有自然排序吗?

假设我有一个像这样的字符向量:

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

我想对它进行单数排序,所以我得到了这个:

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

这是否存在于某个地方,还是我应该开始编码?

4

2 回答 2

45

我不认为“字母数字排序”意味着您认为它的含义。

无论如何,看起来你想要混合排序,它是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"
于 2010-05-06T02:26:23.470 回答
12

自然排序可在stringr/stringi包中使用str_sort()/功能stri_sort()。字母数字和自然排序之间的切换由“数字”参数控制。

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"

伴随函数str_order()/stri_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"
于 2020-02-29T11:34:36.200 回答