1

I need to be able to order my data output from A-Z then AA-ZZ. The problem is, I can only get R to order alphabetically so AA comes before B and C.

Is there a way I can order my data as single letters first then double letters (a, b, c, aa, bb, cc) alphabetically?

markus
  • 25,843
  • 5
  • 39
  • 58
crew4u
  • 45
  • 9
  • 1
    Please be so kind as to post example data and code in a reproducible way. – Andrew Chisholm Dec 28 '19 at 22:10
  • [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with, including a sample of data and what you've tried so far – camille Dec 28 '19 at 22:21

2 Answers2

5

Given

set.seed(1)
x <- sample(c("a", "b", "c", "aa", "bb", "cc"))
x
# [1] "b"  "cc" "c"  "aa" "a"  "bb"

You can do

x[order(nchar(x), x)]
# [1] "a"  "b"  "c"  "aa" "bb" "cc"
markus
  • 25,843
  • 5
  • 39
  • 58
2

We can use unlist withsplit

unlist(lapply(split(v1, nchar(v1)), sort), use.names = FALSE)

data

set.seed(24)
v1 <- sample(c(LETTERS[1:5], strrep(LETTERS[1:5], 2)), 20, replace = TRUE)
akrun
  • 874,273
  • 37
  • 540
  • 662