rvectorsequencerep

Creating a complex sequence in R which skips iterations number without using a loop


The following sequence:

1 2 3 1 2 3 1 2 3

can be generated with a loop

x <- c(); for (i in 1:3) x <- c(x, 1:3)

or (preferably) without a loop

x <- rep(1:3, 3)

Now, I want to remove i from the sequence in the i-th iteration, to get:

2 3 1 3 1 2

It is easy to achieve this by modifying the loop, but how to do this without a loop?


Solution

  • This is an idea:

    x <- rep(1:3, 3)
    x[x != rep(1:3, each = 3)]
    
    # [1] 2 3 1 3 1 2
    

    Another presentation:

    matrix(1:3, 3, 3)[!diag(TRUE, 3)]
    
    # [1] 2 3 1 3 1 2