Numeric to Alphabetic Lettering Function in R

Viewed 764

I have written a function which works on the integers from 1 to 702 for converting a number to a letter in a very specific way. Here are some examples of how I would like the lettering function to work:

  • 1 -> A,
  • 2 -> B,
  • 27 -> AA,
  • 29 -> AC,
  • and so on.

We use this function for "numbering" / "lettering" our appendices in reports. I'm looking to make it more general, such that it can handle positive integers of any size. If I could easily convert the original number to base 26, this would be easier, but I do not see an easy way to do that in R.

appendix_lettering <- function(number) {
  if (number %in% 1:26) {
    return(LETTERS[[number]])
  } else if (number %in% 27:702) {
    first_digit <- (floor((number - 1) / 26))
    second_digit <- ((number - 1) %% 26) + 1
    first_letter <- LETTERS[[first_digit]]
    second_letter <- LETTERS[[second_digit]]
    return(paste0(first_letter, second_letter))
  }
}

Does anyone have suggestions for how I can most easily improve this function to handle any positive integers (or at least many more)?

4 Answers
Related