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

2

5

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?

Kramatorsk answered 5/7, 2023 at 2:17 Comment(1)
Does this answer your question? Repeat vector when its length is not a multiple of desired total lengthAfraid
A
10

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.

Afraid answered 5/7, 2023 at 2:26 Comment(1)
Use rep_len, it is a faster version of length.out: https://mcmap.net/q/1921798/-repeat-vector-when-its-length-is-not-a-multiple-of-desired-total-lengthUndertint
K
6

I think the rep approach by @Mark is the most straightforward and efficient way for you question.

If you are interested in coding practice, you can try defining a function like below

f <- function(v, n) {
    v[(seq(n) - 1) %% length(v) + 1]
}

such that

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

> f(LETTERS[1:5], 9)
[1] "A" "B" "C" "D" "E" "A" "B" "C" "D"

> f(LETTERS[1:3], 9)
[1] "A" "B" "C" "A" "B" "C" "A" "B" "C"
Klondike answered 5/7, 2023 at 4:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.