is there a way to extend LETTERS past 26 characters e.g., AA, AB, AC…?

前端 未结 9 1741
情书的邮戳
情书的邮戳 2020-12-03 00:52

I use LETTERS most of the time for my factors but today I tried to go beyond 26 characters:

LETTERS[1:32]

Expecting there to be an automati

9条回答
  •  广开言路
    2020-12-03 01:39

    A function to produce Excel-style column names, i.e.

    # A, B, ..., Z, AA, AB, ..., AZ, BA, BB, ..., ..., ZZ, AAA, ...
    
    letterwrap <- function(n, depth = 1) {
        args <- lapply(1:depth, FUN = function(x) return(LETTERS))
        x <- do.call(expand.grid, args = list(args, stringsAsFactors = F))
        x <- x[, rev(names(x)), drop = F]
        x <- do.call(paste0, x)
        if (n <= length(x)) return(x[1:n])
        return(c(x, letterwrap(n - length(x), depth = depth + 1)))
    }
    
    letterwrap(26^2 + 52) # through AAZ
    
    ## This will take a few seconds:
    # x <- letterwrap(1e6)
    

    It's probably not the fastest, but it extends indefinitely and is nicely predictable. Took about 20 seconds to produce through 1 million, BDWGN.

    (For a few more details, see here: https://stackoverflow.com/a/21689613/903061)

提交回复
热议问题