问题描述
R 中是否有内置功能可以在考虑大小写的情况下对字符向量进行排序?sort
和 order
忽略大小写:
Is there a builtin functionality in R to sort character vectors taking case into account? sort
and order
ignore the case:
tv <- c("a", "A", "ab", "B")
sort(tv)
## [1] "a" "A" "ab" "B"
这是我目前的解决方案:
This is my solution so far:
CAPS <- grep("^[A-Z]", tv)
c(sort(tv[CAPS]), sort(tv[-CAPS]))
## [1] "A" "B" "a" "ab"
推荐答案
Following 关于 Notepad++ 中自动完成的帖子 您可以更改本地设置:
Following post about Auto-completion in Notepad++ you could change local settings:
Sys.setlocale(, "C")
sort(tv)
# [1] "A" "B" "a" "ab"
编辑.我阅读了 Sys.setlocale
的帮助页面,似乎改变 LC_COLLATE
就足够了:Sys.setlocale("LC_COLLATE", "C")
EDIT. I read help pages to Sys.setlocale
and it seems that changing LC_COLLATE
is sufficient: Sys.setlocale("LC_COLLATE", "C")
要临时更改整理以进行排序,您可以使用 withr
包:
To temporally change collate for sorting you could use withr
package:
withr::with_collate("C", sort(tv))
或使用 stringr
包(如@dracodoc 评论):
or use stringr
package (as in @dracodoc comment):
stringr::str_sort(tv, locale="C")
我认为这是最好的方法.
I think this is the best way to do it.
这篇关于字符串排序时不要忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!