[R] [PS] Switching entries in vector in by groups of two
BEN at SSANET.COM
Fri Jun 27 16:35:03 CEST 2008
xnew <- x[1:length(x)+c(1,-1)]
will do it.
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of David Afshartous
Sent: Friday, June 27, 2008 9:11 AM
To: r-help at r-project.org
Subject: [PS] [R] Switching entries in vector in by groups of two
I have a long vector that contains an even number of entries. I'd like
switch the 1st and 2nd entry, the 3rd and 4th, and so on, without
This code works:
X = c(8, 10, 6, 3, 20, 1)
index = c(2,1,4,3,6,5)
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?
is there a better way?
R-help at r-project.org mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help