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
  • 506,650
  • 124
  • 909
  • 1,183
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
  • 506,650
  • 124
  • 909
  • 1,183
4

We can use seq

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

Or use %%

winners[seq_along(winners) %%2 == 0]
Tensibai
  • 15,304
  • 1
  • 37
  • 55
akrun
  • 789,025
  • 32
  • 460
  • 575
0

You can use the colon operator for this:

winner[2*(1:(length(winner)/2))]
patrickmdnet
  • 3,274
  • 1
  • 28
  • 31