2

I have a vector of values, in which I would like to recursively repeat each element a variable amount of N times according to another vector, using R.

I know how to repeat each element exactly the same N times with repeat(x, each=N), but I cannot figure it out how to generate a variable number of repetitions.

An example:

Vector of values

0.5, 0.3, 0.2, 0.3, 0.1, 0.5, 0.1, 0.7 ....

Vector of repetition

2, 2, 3, 4, 3, 1, 5, 4 ....

Expected result

0.5, 0.5, 0.3, 0.3, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.3, 0.1, 0.1, 0.1, 0.5, 0.1, 0.1, 0.1, 0.1, 0.1, 0.7, 0.7, 0.7, 0.7 ....

I guess some kind of apply function family could work but cannot get the proper code to do it...

Could anyone help?

Many thanks

  • 3
    If your two vectors are `x` and `y`, use `rep(x, y)`. The `rep()` function is for repeating values. – MrFlick May 11 '21 at 16:07
  • 1
    Likely duplicate: https://stackoverflow.com/questions/23818372/more-than-one-value-for-each-argument-in-rep-function-r (Note the all-star answer author). – Ian Campbell May 11 '21 at 16:17

0 Answers0