1

Anyone can help me how to construct the R code. I want to get the element from the vector which is in even position.

The image contains the whole list and i need to pick the elements which is in even position (2,4,6,8,etc).

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
mk11o5
  • 45
  • 2
  • 5

3 Answers3

6

Two observations can be combined to solve this:

  1. Logical indices allow you to pick an element based on a condition:

    c(1, 2)[c(TRUE, FALSE)]
    

    picks the first element but not the second.

  2. Indices that are shorter than your array are recycled until the end of the array:

    letters[c(TRUE, FALSE)]
    

    is the same as

    letters[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, …)]
    

    and picks, 'a', 'c', 'e', etc.

So you can just use:

winner[c(FALSE, TRUE)]
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
4

We can use seq

winners[seq(2, length(winners), by = 2)]

Or use %%

winners[seq_along(winners) %%2 == 0]
Tensibai
  • 15,557
  • 1
  • 37
  • 57
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You can use the colon operator for this:

winner[2*(1:(length(winner)/2))]
patrickmdnet
  • 3,332
  • 1
  • 29
  • 34