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

前端 未结 9 1688
情书的邮戳
情书的邮戳 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:52

    Here's another addition to the list. This seems a bit faster than Gregor's (comparison done on my computer - using length.out = 1e6 his took 12.88 seconds, mine was 6.2), and can also be extended indefinitely. The flip side is that it's 2 functions, not just 1.

    make.chars <- function(length.out, case, n.char = NULL) {
      if(is.null(n.char))
        n.char <- ceiling(log(length.out, 26))
      m <- sapply(n.char:1, function(x) {
        rep(rep(1:26, each = 26^(x-1)) , length.out = length.out)
      })
        m.char <- switch(case,
          'lower' = letters[m],
          'upper' = LETTERS[m]
        )
        m.char <- LETTERS[m]
        dim(m.char) <- dim(m)
    
        apply(m.char, 1, function(x) paste(x, collapse = ""))
    }
    
    
    get.letters <- function(length.out, case = 'upper'){
      max.char <- ceiling(log(length.out, 26))
      grp <- rep(1:max.char, 26^(1:max.char))[1:length.out]
      unlist(lapply(unique(grp), function(n) make.chars(length(grp[grp == n]), case = case, n.char = n)))
    }
    
    
    ##
    make.chars(5, "lower", 2)
    #> [1] "AA" "AB" "AC" "AD" "AE"
    make.chars(5, "lower")
    #> [1] "A" "B" "C" "D" "E"
    make.chars(5, "upper", 4)
    #> [1] "AAAA" "AAAB" "AAAC" "AAAD" "AAAE"
    
    tmp <- get.letters(800)
    head(tmp)
    #> [1] "A" "B" "C" "D" "E" "F"
    tail(tmp)
    #> [1] "ADO" "ADP" "ADQ" "ADR" "ADS" "ADT"
    

    Created on 2019-03-22 by the reprex package (v0.2.1)

    0 讨论(0)
  • 2020-12-03 01:54

    You can make what you want like this:

    LETTERS2<-c(LETTERS[1:26], paste0("A",LETTERS[1:26]))
    
    0 讨论(0)
  • 2020-12-03 01:56

    A little late to the party, but I want to play too.

    You can also use sub, and sprintf in place of paste0 and get a length 702 vector.

    c(LETTERS, sapply(LETTERS, sub, pattern = " ", x = sprintf("%2s", LETTERS)))
    
    0 讨论(0)
提交回复
热议问题