1

I need to create the vector cx=(1, 1, 1, 2, 2, 2, 3, 3, 3). I have wrote a code.

k <- 3
tmp <- matrix(0, k, k)
tmp[1,] <-rep(c(1), times = k)
tmp[2,] <-rep(c(2), times = k)
tmp[3,] <-rep(c(3), times = k)

cx <-c(t(tmp))
cx
#[1] 1 1 1 2 2 2 3 3 3

Result is right for me but the code is very long. How to rewrite code for arbitrary number k? My variant is:

k <- 3
tmp <- matrix(0, k, k)
for(i in 1:k) tmp[i,] <-rep(c(i), times = k)
cx <-c(t(tmp))
Nick
  • 1,086
  • 7
  • 21

1 Answers1

3

rep function is good enough, but the Kronecker product is worth mentioning.

kronecker(1:3, rep(1, 3))
Kota Mori
  • 6,510
  • 1
  • 21
  • 25