PeterD
PeterD

Reputation: 439

How to repeat the indices of a vector based on the values of that same vector?

Given a random integer vector below:

z <- c(3, 2, 4, 2, 1)

I'd like to create a new vector that contains all z's indices a number of times specified by the value corresponding to that element of z. To illustrate this. The desired result in this case should be:

[1] 1 1 1 2 2 3 3 3 3 4 4 5

There must be a simple way to do this.

Upvotes: 2

Views: 673

Answers (2)

GKi
GKi

Reputation: 39667

You can use rep and seq to repeat the indices of a vector based on the values of that same vector. seq to get the indices and rep to repeat them.

rep(seq(z), z)
# [1] 1 1 1 2 2 3 3 3 3 4 4 5

Upvotes: 4

PeterD
PeterD

Reputation: 439

Starting with all the indices of the vector z. These are given by:

1:length(z)

Then these elements should be repeated. The number of times these numbers should be repeated is specified by the values of z. This can be done using a combination of the lapply or sapply function and the rep function:

unlist(lapply(X = 1:length(z), FUN = function(x) rep(x = x, times = z[x])))
[1] 1 1 1 2 2 3 3 3 3 4 4 5

unlist(sapply(X = 1:length(z), FUN = function(x) rep(x = x, times = z[x])))
[1] 1 1 1 2 2 3 3 3 3 4 4 5

Both alternatives give the same result.

Upvotes: 0

Related Questions