Repeating a numerical vector

Viewed 35

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.

2 Answers

Try rep with each = 3

> rep(1:3, each = 3)
[1] 1 1 1 2 2 2 3 3 3

or kronecker

> kronecker(1:3, rep(1, 3))
[1] 1 1 1 2 2 2 3 3 3

or replicate

> c(t(replicate(3, 1:3)))
[1] 1 1 1 2 2 2 3 3 3

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
Related