Search code examples
rvectorelement

Grab always n elements from vector, if vector length <n, loop over vector again


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?


Solution

  • You can use the rep_len() function:

    > rep_len(LETTERS[1:15], 9)
    [1] "A" "B" "C" "D" "E" "F" "G" "H" "I"
    > rep_len(LETTERS[1:5], 9)
    [1] "A" "B" "C" "D" "E" "A" "B" "C" "D"
    > rep_len(LETTERS[1:3], 9)
    [1] "A" "B" "C" "A" "B" "C" "A" "B" "C"
    

    Alternatively, there is also the rep() function, with the length.out argument, which would give you the same result, however rep() is slightly slower than rep_len().

    You can read the documentation here.