3

Suppose I have a numeric vector v

v <- 1:5

I want to rep

v[1] by v[1] times.

v[2] by v[2] times... and so on....

The desired output would be:

1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 

The following does not work. Got any ideas?

rep(v, each = function(x) v[x]) 

Many thanks in advance.

geom_na
  • 258
  • 2
  • 10

1 Answers1

6

We can use rep on itself

rep(v, v)

If we want to specify the argument, use times

rep(v, times = v)

The each would not take anonymous function and it takes only a vector of length 1. According to ?rep

each - non-negative integer. Each element of x is repeated each times. Other inputs will be coerced to an integer or double vector and the first element taken. Treated as 1 if NA or invalid.

akrun
  • 874,273
  • 37
  • 540
  • 662