Skip to content
Prev 342394 / 398498 Next

odd, even indices of a vector

Hi Carol,
On 07/21/2014 01:33 PM, carol white wrote:
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.