1

Why can't I sort this vector sort(c("r_1", "r_2", "r_10")) asr_1, r_2, r_10?

The result is:

"r_1"  "r_10" "r_2" 
xhr489
  • 1,957
  • 13
  • 39

1 Answers1

3

We can use mixed_sort from gtools. According to ?mixed_sort

These functions sort or order character strings containing embedded numbers so that the numbers are numerically sorted rather than sorted by character value.

library(gtools)
mixedsort(v1)
#[1] "r_1"  "r_2"  "r_10"

The reason for the sort is that it is not a numeric vector. So, sorting happen

data

v1 <- c("r_1", "r_2", "r_10")
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662