repeating vector of letters

前端 未结 6 1299
野的像风
野的像风 2020-12-17 17:59

Is there a function to create a repeating list of letters in R?

something like

letters[1:30]
[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i         


        
6条回答
  •  [愿得一人]
    2020-12-17 18:51

    There is almost certainly a better way, but this is what I ended up with:

    letter_wrap <- function(idx) {  
      vapply(
        idx,
        function(x) 
          paste0(
            rep(
              letters[replace(x %% 26, !x %% 26, 26)], 1 + (x - 1) %/% 26 ), collapse=""), "")
    }
    letter_wrap(1:60)
    #  [1] "a"   "b"   "c"   "d"   "e"   "f"   "g"   "h"   "i"   "j"   "k"   "l"   "m"   "n"  
    # [15] "o"   "p"   "q"   "r"   "s"   "t"   "u"   "v"   "w"   "x"   "y"   "z"   "aa"  "bb" 
    # [29] "cc"  "dd"  "ee"  "ff"  "gg"  "hh"  "ii"  "jj"  "kk"  "ll"  "mm"  "nn"  "oo"  "pp" 
    # [43] "qq"  "rr"  "ss"  "tt"  "uu"  "vv"  "ww"  "xx"  "yy"  "zz"  "aaa" "bbb" "ccc" "ffffd"
    # [57] "eee" "fff" "ggg" "hhh"
    

    EDIT: failed to notice Ananda's answer before I posted this one. This one is different enough that I'm leaving it. Note it takes the index vector as an input, as opposed to the number of items.

提交回复
热议问题