问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/18993010/replicating-vector-elements-by-index