Replicating vector elements by index

妖精的绣舞 提交于 2019-12-02 12:18:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!