Search code examples
rapplyrep

Alternating between values with rep() in R


I am looking for an elegant way of repeating two values according to a given vector in an alternating fashion. It is better stated by example. Take the following code for instance:

vals_to_rep <- c(1, 2)
tms_to_rep <- c(5, 4, 15)
res <- c(rep(1, 5), rep(2, 4), rep(1, 15))
res

In this example, I wish to repeat the values 1 and 2 according to the vector tms_to_rep where I will be starting with 1 (given it is first in the variable) vals_to_rep, before alternating to 2, back to 1, ...

I wish to continue this process for the length of tms_to_rep-- in this case, three times. The result would look like this:

1 1 1 1 1 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

If it helps, you can assume vals_to_rep is binary, but no assumptions on length of tms_to_rep.

Thanks!


Solution

  • You can expand vals_to_rep out to the length of tms_to_rep. Then rep() works fine:

    vals_to_rep_expanded = rep(vals_to_rep, length.out = length(tms_to_rep))
    rep(vals_to_rep_expanded, times = tms_to_rep)