rrowsswap

R: Swapping every second row in an array


I'm looking to swap second every row in an array. I do not know the length of the array beforehand. I do, however, know that it will be divisible by 2.

As an example:

101 102 147 148

would become

102 101 148 147

Any help would be greatly appreciated.

Thanks

Mike


Solution

  • Let's say your vector ("array" is sooo Fortran) is x.

    even <- seq(from=2, to=length(x), by=2)
    odd <- even - 1
    xnew <- x
    xnew[even] <- x[odd]
    xnew[odd] <- x[even]
    

    You could make the code more terse, but this probably makes it easier to see what's going on.