Repeating Vector of Letters

repeating vector of letters

It's not too difficult to piece together a quick function to do something like this:

myLetters <- function(length.out) {
a <- rep(letters, length.out = length.out)
grp <- cumsum(a == "a")
vapply(seq_along(a),
function(x) paste(rep(a[x], grp[x]), collapse = ""),
character(1L))
}
myLetters(60)
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l"
# [13] "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x"
# [25] "y" "z" "aa" "bb" "cc" "dd" "ee" "ff" "gg" "hh" "ii" "jj"
# [37] "kk" "ll" "mm" "nn" "oo" "pp" "qq" "rr" "ss" "tt" "uu" "vv"
# [49] "ww" "xx" "yy" "zz" "aaa" "bbb" "ccc" "ddd" "eee" "fff" "ggg" "hhh"

Repeating a vector of names in a column over each date

Don't use map; you can take advantage of vector recycling. Just repeat each element of date_range 4 times.

DF <- data.frame(date = rep(date_range, each = 4), 
Source = c("a", "b", "c", "d"))

head(DF)
date Source
1 2015-01-01 a
2 2015-01-01 b
3 2015-01-01 c
4 2015-01-01 d
5 2015-02-01 a
6 2015-02-01 b
7 2015-02-01 c
8 2015-02-01 d
9 2015-03-01 a
10 2015-03-01 b

Another option with tidyr::separate_rows:

library(tidyr)
data.frame(date = date_range, Source = c("a,b,c,d")) %>%
separate_rows(Source)

Generate vector of a repeated string with incremental suffix number

An alternative to paste is sprintf, which can be a bit more convenient if, for instance, you wanted to "pad" your digits with leading zeroes.

Here's an example:

sprintf("Fst%d", 1:10)     ## No padding
# [1] "Fst1" "Fst2" "Fst3" "Fst4" "Fst5"
# [6] "Fst6" "Fst7" "Fst8" "Fst9" "Fst10"
sprintf("Fst%02d", 1:10) ## Pads anything less than two digits with zero
# [1] "Fst01" "Fst02" "Fst03" "Fst04" "Fst05"
# [6] "Fst06" "Fst07" "Fst08" "Fst09" "Fst10"

So, for your question, you would be looking at:

sprintf("Fst%d", 1:100) ## or sprintf("Fst%03d", 1:100)


Related Topics



Leave a reply



Submit