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

How to remove numeric values as character and resort the string accordng unit number

I have this string

 D = c("0" , "11", "12", "13", "14", "15", "16", "21", "22", "23", "24", "25", "26", "31", "32", "33", "34", "35", "36", "41", "42", "43", "44","45", "46","51","52", "53", "54", "55", "56", "61", "62", "63", "64", "65", "66") 
  1. If I would to remove those character lower then 30 without transforming the string as numeric, what should I do?

  2. If I would like to reorder the string basing on the unit number (meaning that all those with final 1 go before those with final two and so on, such 31, 41, 51, 61, 32, 42 and so on, which should be the opration?

    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

Thanks

>Solution :

You don’t have to convert to numeric, D[D >= 30] works fine. >= works also for character vectors and the sorting depends then on your locale. Check ?Comparison for more details.

D[D >= "30"]
#[1] "31" "32" "33" "34" "35" "36" "41" "42" "43" "44" "45" "46" "51" "52" "53" "54" "55" "56" "61" "62" "63" "64" "65" "66"

For the sorting, this will work (but probably only if you have 2-digit numbers):

str_rev <- stringi::stri_reverse
str_rev(sort(str_rev(D[D >= "30"])))
# [1] "31" "41" "51" "61" "32" "42" "52" "62" "33" "43" "53" "63" "34" "44" "54" "64" "35"
#[18] "45" "55" "65" "36" "46" "56" "66"

Or with str_sub:

library(stringr)        
D[order(str_sub(D, -1, -1))]
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