Do not ignore case when sorting character strings

Is there any built-in functionality in R for sorting character vectors that are case-sensitive? sortand orderignore the case:

tv <- c("a", "A", "ab", "B")
sort(tv)
## [1] "a"  "A"  "ab" "B" 

This is my decision:

CAPS <- grep("^[A-Z]", tv)
c(sort(tv[CAPS]), sort(tv[-CAPS]))
## [1] "A"  "B"  "a"  "ab"
+5
source share
1 answer

After reporting completion in Notepad ++, you can change the local settings:

Sys.setlocale(, "C")
sort(tv)
# [1] "A"  "B"  "a"  "ab"

EDIT. I am reading the help pages Sys.setlocaleand it seems that changing is LC_COLLATEenough:Sys.setlocale("LC_COLLATE", "C")

You can flip it into a function if you use it more than once:

sortC <- function(...) {
    a <- Sys.getlocale("LC_COLLATE")
    on.exit(Sys.setlocale("LC_COLLATE", a))
    Sys.setlocale("LC_COLLATE", "C")
    sort(...)
}
+10
source

All Articles