[R] Switching entries in vector in by groups of two

Marc Schwartz marc_schwartz at comcast.net
Fri Jun 27 16:17:09 CEST 2008


on 06/27/2008 09:11 AM David Afshartous wrote:
> All,
> 
> I have a long vector that contains an even number of entries. I'd like to
> switch the 1st and 2nd entry, the 3rd and 4th, and so on, without writing a
> loop.
> 
> This code works:
> 
> X = c(8, 10, 6, 3, 20, 1)
> index = c(2,1,4,3,6,5)
> X[index]
> 
> But for a long list is there a way to generate the index?  I can get the
> parts to the index as:
> 
> index.odd = seq(1,length(X), by  = 2)
> index.even = index.odd + 1
> 
> Is there a simple way to interweave them to produce the desired index?  Or
> is there a better way?
> 
> Cheers,
> David

How about this:

 > as.vector(t(matrix(X, ncol = 2, byrow = TRUE)[, 2:1]))
[1] 10  8  3  6  1 20

Trying a longer vector as well:

 > Vec <- sample(20)

 > Vec
  [1] 13 20 14 10 12  7  3 19 11 15  1  4  9 18  6  8  5 16 17  2

 > as.vector(t(matrix(Vec, ncol = 2, byrow = TRUE)[, 2:1]))
  [1] 20 13 10 14  7 12 19  3 15 11  4  1 18  9  8  6 16  5  2 17


HTH,

Marc Schwartz



More information about the R-help mailing list