Dear list, is there a command that selects every second value from a given vector? For instance, a <- c(1,2,3,4,5,6) should yield 1,3,5 and 2,4,6 which i intend to place into two seperate vectors. best Alex
try this: a <- c(1,2,3,4,5,6) n <- length(a) a[seq(1, n, 2)] a[seq(2, n, 2)] I hope it helps. Best, Dimitris Walther, Alexander wrote:> Dear list, > > is there a command that selects every second value from a given vector? > For instance, > > a <- c(1,2,3,4,5,6) > > should yield > > 1,3,5 > > and > > 2,4,6 > > which i intend to place into two seperate vectors. > > > best > > Alex > > ______________________________________________ > 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. >-- Dimitris Rizopoulos Assistant Professor Department of Biostatistics Erasmus University Medical Center Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands Tel: +31/(0)10/7043478 Fax: +31/(0)10/7043014
Instead of making two vectors, you might want to just have one matrix with two rows: amat <- matrix(a, nrow=2) Then you can do: amat[1,] amat[2,] Patrick Burns patrick at burns-stat.com +44 (0)20 8525 0696 http://www.burns-stat.com (home of "The R Inferno" and "A Guide for the Unwilling S User") Walther, Alexander wrote:> Dear list, > > is there a command that selects every second value from a given vector? > For instance, > > a <- c(1,2,3,4,5,6) > > should yield > > 1,3,5 > > and > > 2,4,6 > > which i intend to place into two seperate vectors. > > > best > > Alex > > ______________________________________________ > 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. >
In addition to the other suggestions, you can use logical subsetting with autoreplication:> x <- 1:6 > x[ c(T,F) ][1] 1 3 5> x[ c(F,T) ][1] 2 4 6 -- Gregory (Greg) L. Snow Ph.D. Statistical Data Center Intermountain Healthcare greg.snow at imail.org 801.408.8111> -----Original Message----- > From: r-help-bounces at r-project.org [mailto:r-help-bounces at r- > project.org] On Behalf Of Walther, Alexander > Sent: Sunday, January 17, 2010 4:20 AM > To: r-help at r-project.org > Subject: [R] Choose every second value > > Dear list, > > is there a command that selects every second value from a given vector? > For instance, > > a <- c(1,2,3,4,5,6) > > should yield > > 1,3,5 > > and > > 2,4,6 > > which i intend to place into two seperate vectors. > > > best > > Alex > > ______________________________________________ > 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.