2

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.

Wietze
  • 109
  • 7

2 Answers2

4

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

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
Pedro Alencar
  • 1,049
  • 7
  • 20