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

Gabor Grothendieck ggrothendieck at gmail.com
Fri Jun 27 16:14:01 CEST 2008


You can do it without and index like this:

c(matrix(X, 2)[2:1,])

or if you need the index for some purpose apart from this:

c(matrix(seq_along(X), 2)[2:1,])

On Fri, Jun 27, 2008 at 10:11 AM, David Afshartous
<dafshartous at med.miami.edu> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list