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")
If I would to remove those character lower then 30 without transforming the string as numeric, what should I do?
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?
Thanks
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))]