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

From: Henrique Dallazuanna <wwwhsd_at_gmail.com>
Date: Fri, 27 Jun 2008 11:17:45 -0300

Try this:

ave(X, rep(1:(length(X)/2), each = 2), FUN=rev)

On Fri, Jun 27, 2008 at 11: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.
>

-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O

	[[alternative HTML version deleted]]


______________________________________________ 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.

Received on Fri 27 Jun 2008 - 14:27:46 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 27 Jun 2008 - 15:01:14 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive