Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading