Skip to content
Prev 54254 / 63424 Next

split() - unexpected sorting of results

Hello,

In order to solve that problem of sorting numerics made characters there 
is package stringr, functions str_sort and str_order.

library(stringr)

set.seed(2447)

x <- sample(11L)
sort(as.character(x))
[1] "1"  "10" "11" "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"

str_sort(as.character(x), numeric = TRUE)
[1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11"

str_order(as.character(x), numeric = TRUE)
#[1]  1  4 11  8  6  5  3 10  9  7  2

i <- str_order(as.character(x), numeric = TRUE)
as.character(x)[i]
#[1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11"


Unfortunately this does not solve the OP's question, factor(), 
as.factor(), split() and others use the base R sorter and this can only 
be changed by changing their sources.

Hope this helps,

Rui Barradas

Em 21-10-2017 00:32, Herv? Pag?s escreveu: