Search code examples
ralgorithmswitch-statementpermute

Switching the first element with the last one in a loop


Is there a function in R which switches the first element with the last one in a vector? I have a for loop which need that reordering. From:

months = seq(1:12)
[1]  1  2  3  4  5  6  7  8  9 10 11 12

I would like to have:

[1]  12 1  2  3  4  5  6  7  8  9 10 11

and then again:

[1]  11 12  1  2  3  4  5  6  7  8  9 10

... until the 12th position.


Solution

  • I'm afraid that you have to come up with a home-made function, something like this one:

    rotate <- function(v,i=1) {
      i <- i %% length(v)
      if (i==0) return(v)
      v[c(seq(i+1,length(v)),seq(i))]
    }
    

    Couple of examples:

    v <- seq(12)
    rotate(v,1)
    # [1]  2  3  4  5  6  7  8  9 10 11 12  1
    
    rotate(v,-1)
    # [1] 12  1  2  3  4  5  6  7  8  9 10 11