如何在 R 中执行自然(字典顺序)排序?

发布于 2024-08-31 07:34:54 字数 382 浏览 6 评论 0原文

R 是否有自然排序

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

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

我想按字母顺序对它进行排序,所以我得到这个:

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

飘逸的'云 2024-09-07 07:34:54

我不认为“字母数字排序”意味着你认为的意思。

无论如何,看起来您想要混合排序,它是 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"

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"
只有影子陪我不离不弃 2024-09-07 07:34:54

自然排序可在 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"

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文