Search code examples
rvectorseqrep

How do I use seq() and rep() and paste() to generate a specific vector?


I am trying to generate the following vector without using c(): a1, b2, b3, c4, c4, c6. I am having a really hard time with this. I tried to make a simple python function to help visualize it:

listy = []
size = 2
lets = ["a", "b", "c"]
iterator = 1
for i in range(1, 4):
    let = lets[i-1]
    for j in range(3-size):
        listy.append(let + str(iterator))
        iterator += 1
    size -= 1
print(listy)

But I can't get anything similar to work in R. I would greatly appreciate some help. About the closest I've gotten is this:

paste(rep(1:6), rep(letters[1:3]))

But obviously that's way off. Am I going to have to use for loops to generate this? It seems like there must be a simpler way... I am new to vector generation and the functions don't seem intuitive at all. If you could just give a poke in the right direction I'm sure I could figure it out. Thanks!


Solution

  • One way would be :

    vec <- letters[1:3]
    tmp <- rep(vec, seq_along(vec))
    paste0(tmp, seq_along(tmp))
    #[1] "a1" "b2" "b3" "c4" "c5" "c6"
    

    By hardcoding this is similar to :

    paste0(rep(c('a', 'b', 'c'), 1:3), 1:6)