Search code examples
rvectorreverse

How to reverse the order of each two consecutive elements in a vector?


Let's say I have the following vector

x = c(1,2,3,4,5,6)

I wish to reverse the order of each two consecutive elements as follows

2 1 4 3 6 5

Solution

  • You can use ave + rev to reverse the vector by group:

    ave(x, (seq_along(x) + 1) %/% 2, FUN = rev)
    #[1] 2 1 4 3 6 5