user1701545
user1701545

Reputation: 6200

Replicating vector elements by index

I have an integer vector: a <- c(1,1,3,1,4) where each element in a indicates how many times its index should be replicated in a new vector.

So the resulting vector should be: b <- c(1,2,3,3,3,4,5,5,5,5)

What would be the most efficient way to do this?

Upvotes: 1

Views: 85

Answers (1)

agstudy
agstudy

Reputation: 121578

For example using rep:

rep(seq_along(a),a)
1 2 3 3 3 4 5 5 5 5

Another less efficient option is to use inverse.rle :

inverse.rle(list(lengths=a,values=seq_along(a)))
[1] 1 2 3 3 3 4 5 5 5 5

Upvotes: 3

Related Questions