"numeric to alphabetic lettering function in r " Code Answer


here are some alternatives:

1) encode let b be the base. here b = 26. then there are b^k appendices having k letters so for a particular appendix having number x it has n letters if n is the smallest integer for which b + b^2 + ... + b^n >= x. the lhs of this inequality is a geometric series and therefore has a closed form solution. replacing the lhs with that expression and solving the resulting equation for n gives the formula for n in the code below. then we subtract all b^k terms from number for which k < n and use the apl-like encode function found here (and elsewhere on the web). encode does the base conversion giving digits, a vector of digits in base base. finally add 1 to each digit and use that as a lookup into letters.

app2 <- function(number, base = 26) {
    n <- ceiling(log((1/(1 - base) - 1 - number) * (1 - base), base = base)) - 1
    digits <- encode(number - sum(base^seq(0, n-1)), rep(base, n))
    paste(letters[digits + 1], collapse = "")

sapply(1:29, app2) # test


[1] "a"  "b"  "c"  "d"  "e"  "f"  "g"  "h"  "i"  "j"  "k"  "l"  "m"  "n"  "o" 
[16] "p"  "q"  "r"  "s"  "t"  "u"  "v"  "w"  "x"  "y"  "z"  "aa" "ab" "ac"

another test to try is:

sapply(1:60, app2, base = 3)

2) recursive solution here is an alternative that works recursively. it computes the last letter of the appendix number and then removes it and recursively computes the portion to its left.

app2r <- function(number, base = 26, suffix = "") {
   number1 <- number - 1
   last_digit <- number1 %% base
   rest <- number1 %/% base
   suffix <- paste0(letters[last_digit + 1], suffix)
   if (rest > 0) recall(rest, base, suffix) else suffix

# tests
identical(sapply(1:29, app2r), sapply(1:29, app2))
## [1] true
identical(sapply(1:60, app2r, base = 3), sapply(1:60, app2, base = 3))
## [1] true
By Nanthini Muniapan on April 14 2022

Answers related to “numeric to alphabetic lettering function in r ”

Only authorized users can answer the Search term. Please sign in first, or register a free account.