Replicate each element in a vector different times in R [duplicate]

ε祈祈猫儿з 提交于 2020-07-30 09:24:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/61977239/replicate-each-element-in-a-vector-different-times-in-r

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