2

I have a character vector like the following:

char <- c("C.1", "C.3", "C.10", "A.5", "D.4", "A.50", "A.49")

I want to sort them in alphabetical order, but if I do

char[order(char)]

I get

[1] "A.49" "A.5"  "A.50" "C.1"  "C.10" "C.3"  "D.4" 

However, the desired output is A.5, A.49, A.50, C.1, C.3, C.10, D.4 as I would like to preserve the order of the actual numbers themselves.

How can I reorder char like this?

Keshav M
  • 1,309
  • 1
  • 13
  • 24

1 Answers1

1

I'm sure there are many ways to do this. Here is one example using stringr. I extract the letter and feed that in as the first argument to order, next I extract the digit and use that as the second argument to order.

library(stringr)
char[order(str_extract(char,"\\w"), strtoi(str_extract(char,"\\d+")))]
# [1] "A.5"  "A.49" "A.50" "C.1"  "C.3"  "C.10" "D.4" 
jasbner
  • 2,253
  • 12
  • 24