how to append to a list after its last element in loop in R?

Viewed 152

I have vector name: block_sizes=c(3,3,4) and I want to make a list which it has block_sizes[1] number of 1s,block_sizes[2] number of 2s ,and block_sizes[3] of 3s, etc.

In this example, I should give [3,3,4] to my code and get [1,1,1,2,2,2,3,3,3,3].

I wrote the code below, but I don't know why it gives me [0,3,3,3,3]. I think it is because I should have appended to last element of vector which I am not now. Any input is appreciated.

vector=0
for (i in length(block_sizes )) {
  buf=rep.int(i,times =block_sizes[i])
  membership_vector=append(vector,buf)

  }```
2 Answers

We can use rep without any loop as the times parameter is vectorized

rep(seq_along(block_sizes), block_sizes)
#[1] 1 1 1 2 2 2 3 3 3 3

Or for the faster implementation

rep.int(seq_along(block_sizes), times = block_sizes)
#[1] 1 1 1 2 2 2 3 3 3 3

Or if we need a loop

v1 <- c()
for(i in seq_along(block_sizes)) {
   v1 <- c(v1, rep.int(i, times = block_sizes[i]))
 }

data

block_sizes <- c(3, 3, 4)

We can use mapply:

unlist(mapply(rep, c(1,2,3), c(3,3,4))

# [1] 1 1 1 2 2 2 3 3 3 3
Related