问题
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