Say I have a set of vectors of different lengths.
I want to grab always the first 9 elements from them.
However, if the vector length is <9, I want to grab all the elements, and complete up to 9 going over the vector again (and again, and again… where necessary) from the start.
For example:
v1=LETTERS[1:15] -> I want to grab "A" "B" "C" "D" "E" "F" "G" "H" "I"
v2=LETTERS[1:5] -> I want to grab "A" "B" "C" "D" "E" "A" "B" "C" "D"
v3=LETTERS[1:3] -> I want to grab "A" "B" "C" "A" "B" "C" "A" "B" "C"
… and so on.
Is there a simple way to do this without going over loops and exceptions? Thanks!
>Solution :
You can use the rep() function:
> rep(LETTERS[1:15], length.out = 9)
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I"
> rep(LETTERS[1:5], length.out = 9)
[1] "A" "B" "C" "D" "E" "A" "B" "C" "D"
> rep(LETTERS[1:3], length.out = 9)
[1] "A" "B" "C" "A" "B" "C" "A" "B" "C"
Read the documentation here.