Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R order list based on multiple characters from each item

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading