Reputation: 400
Say I have a sequence from 1 to (a+b)*q, I would like to select the 1st "a" elements and skip the following "b" elements and repeat. For example
a = 5; b = 4; q = 3
seq(1, (a+b)*q)
1:27
a <- c(1:5, 10:14, 19:23)
For sequences > 1000, it is hard to do it manually, so is there a way to with a code?
Upvotes: 2
Views: 179
Reputation: 160417
We can take advantage of "recycling" of arguments/indices:
seq(1, (a+b)*q)[c(rep(TRUE,5),rep(FALSE,4))]
# [1] 1 2 3 4 5 10 11 12 13 14 19 20 21 22 23
Recycling here means that the indices are of length 9, but the vector itself is length 27, a multiple of 9. This means that the 9 indices are repeated three times consecutively.
When it is not a clear multiple, though, R may not tell you anything. Let's change the "4" to a "3", where length 8 does not go evenly into 27:
seq(1, (a+b)*q)[c(rep(TRUE,5),rep(FALSE,3))]
# [1] 1 2 3 4 5 9 10 11 12 13 17 18 19 20 21 25 26 27
# ^^^^^^^^^^^^^ ------------- ^^^^^^^^^^^^^^ --------
# len5 gap3 len5 gap3 len5 gap3 len3
So while the 5/3/5/3/... cycling is consistent, it doesn't necessarily end on a 5. If that's okay, then you're good. If not, you should add in some logical to catch this type of mismatch.
Upvotes: 4