Search code examples
rfor-loopvectorrep

Repeating a numerical vector


Suppose I have the following numerical vector

z = 1:3
f <-c(rep(z[1],3),rep(z[2],3),rep(z[3],3))
[1] 1 1 1 2 2 2 3 3 3

Now suppose the following:

z =1:i #i is an interger

How do I write a function such I obtain the same output format as in the first line of code? I tried a for-loop but did not get the desired result.


Solution

  • Using for-loop:

    z <- 3
    vector <- c()
    for (i in 1:z){
        vector <- append(vector, rep(i,z))
    }
    
    > vector
    [1] 1 1 1 2 2 2 3 3 3