1

I have a vector,

x<-c(1,3,2,3,1,4,2,1,3,4,2,1,0,2,4,5,2,1,2)

I would like to obtain a vector of x by not including one every other time starting from the first element up to the 10th element. This will be to include elements (1,3,5,7 and 9 of x) to obtain (1,2,1,2,3). In line with the below expression which produces an error.

x[1:10,by=2]

Thank you

Barnaby
  • 1,472
  • 4
  • 20
  • 34

3 Answers3

6

You may use

x[seq(1, 10, by=2)]    

In this way with seq(1, 10, by=2) you generate the indexes of x - elements and then you get them from x with [] operator.

cenka
  • 221
  • 1
  • 7
3

Here's another way could do this, although the above suggestions are more straight forward

x[1:10%%2 != 0][1:5]

Similar way (probably better) suggested by @SimonO'Hanlon

x[c(TRUE, FALSE)][1:5]
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
2

You can do this:

x[seq(from=1,to=10, by=2)]
Daniel Falbel
  • 1,721
  • 1
  • 21
  • 41