[R] odd, even indices of a vector

Hervé Pagès hpages at fhcrc.org
Tue Jul 22 07:37:59 CEST 2014


Hi Carol,

On 07/21/2014 01:33 PM, carol white wrote:
> Might be a trivial question but how to identify the odd and even indices of a vector?
>
> x = c(1,z,w,2,6,7)
>
> el of odd indices= 1,w,6
> el of even indices= z,2,7

The easiest way is to subset your vector with c(TRUE, FALSE) to keep
only the odd indices:

   > letters[c(TRUE, FALSE)]
   [1] "a" "c" "e" "g" "i" "k" "m" "o" "q" "s" "u" "w" "y"

and with c(FALSE, TRUE) to keep only the even indices:

   > letters[c(FALSE, TRUE)]
   [1] "b" "d" "f" "h" "j" "l" "n" "p" "r" "t" "v" "x" "z"

Note that the above doesn't work properly with vector of length < 2.

A method that works independently of the length of the vector (using
the is.odd and is.even functions from the "identifying odd or even
number" post that you referred to):

   x[is.odd(seq_along(x))]

   x[is.even(seq_along(x))]

Hope this helps,
H.

>
> given the def of odd and even in https://stat.ethz.ch/pipermail/r-help/2010-July/244299.html
>
> should a loop be used?
>
> for (i in 1: length(x))
> if (is.odd(i)) print (i)
>
>
> Carol
>
> 	[[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.
>

-- 
Hervé Pagès

Program in Computational Biology
Division of Public Health Sciences
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N, M1-B514
P.O. Box 19024
Seattle, WA 98109-1024

E-mail: hpages at fhcrc.org
Phone:  (206) 667-5791
Fax:    (206) 667-1319



More information about the R-help mailing list