I’d like to sort a list based on more than the first character of each item in that list. The list contains chr data though some of those characters are digits. I’ve been trying to use a combination of substr() and order but to no avail.
For example:
mylist <- c('0_times','3-10_times','11_20_times','1-2_times','more_than_20_times')
mylist[order(substr(mylist,1,2))]
However, this results in 11-20_times being placed prior to 3-10_times:
[1] "0_times" "1-2_times" "11-20_times" "3-10_times" "more_than_20_times"
>Solution :
This requires a bit of string parsing and converting to numeric:
o <- sapply(strsplit(mylist, '\\D+'), function(x) min(as.numeric(x[nzchar(x)])))
mylist[order(o)]
#> [1] "0_times" "1-2_times" "3-10_times"
#> [4] "11_20_times" "more_than_20_times"