【问题标题】:What are the R sorting rules of character vectors?字符向量的R排序规则是什么?
【发布时间】:2011-08-29 11:22:05
【问题描述】:

R 按我描述为字母而不是 ASCII 的序列对字符向量进行排序。

例如:

sort(c("dog", "Cat", "Dog", "cat"))
[1] "cat" "Cat" "dog" "Dog"

三个问题:

  1. 描述这种排序顺序的技术正确术语是什么?
  2. 我在 CRAN 的手册中找不到对此的任何参考。在哪里可以找到 R 中排序规则的说明?
  3. 这与其他语言(如 C、Java、Perl 或 PHP)中的此类行为有什么不同?

【问题讨论】:

标签: r sorting


【解决方案1】:

Details: 代表sort() 状态:

 The sort order for character vectors will depend on the collating
 sequence of the locale in use: see ‘Comparison’.  The sort order
 for factors is the order of their levels (which is particularly
 appropriate for ordered factors).

然后help(Comparison) 显示:

 Comparison of strings in character vectors is lexicographicwithin
 the strings using the collating sequence of the locale in use:see
 ‘locales’.  The collating sequence of locales such as ‘en_US’ is
 normally different from ‘C’ (which should use ASCII) and can be
 surprising.  Beware of making _any_ assumptions about the 
 collation order: e.g. in Estonian ‘Z’ comes between ‘S’ and ‘T’,
 and collation is not necessarily character-by-character - in
 Danish ‘aa’ sorts as a single letter, after ‘z’.  In Welsh ‘ng’
 may or may not be a single sorting unit: if it is it follows ‘g’.
 Some platforms may not respect the locale and always sort in
 numerical order of the bytes in an 8-bit locale, or in Unicode
 point order for a UTF-8 locale (and may not sort in the same order
 for the same language in different character sets).  Collation of
 non-letters (spaces, punctuation signs, hyphens, fractions and so
 on) is even more problematic.

所以这取决于您的区域设置。

【讨论】:

  • 哦。我试图在cran.r-project.org/doc/manuals/R-ints.html 中找到这个。谢谢。
  • 我不会尝试改进 Dirk 和帮助的描述,但在 R 之外,人们可能会发现它被描述为字典排序,尽管大小写不变。排序规则是一个严肃的考虑因素,因为幼稚的文本处理通常是针对英语顺序进行的,这对其他一些语言是不利的。一个很好的例子是,对于母语人士只考虑严格 A-Z 顺序的 26 个字母的人来说,它使名称排序看起来很奇怪。
  • 我刚刚花了很长时间才发现空格字符可能会或可能不会被忽略,并且这取决于我是在本地运行测试还是在执行R CMD check
  • 更好的方法是使用stringr::str_sort,您可以指定区域设置,这样结果就会一致。
  • 仅当您愿意或被要求接受stringr 依赖的较重负担时。
【解决方案2】:

排序取决于语言环境。 我的解决方案如下...

我创建~/.Renviron 文件

cat ~/.Renviron 
#LC_ALL=C

那么在 R 中排序是在 C 语言环境中

x=c("A", "B", "d", "F", "g", "H")
sort(x)
#[1] "A" "B" "F" "H" "d" "g"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-16
    • 2015-10-26
    • 2016-03-23
    • 2011-07-28
    • 2011-10-09
    • 1970-01-01
    • 2019-10-11
    • 2016-06-18
    相关资源
    最近更新 更多