Select every other element from a vector
Asked Answered
C

3

68

Let's say I had a vector:

remove <- c(17, 18, 19, 20, 24, 25, 30, 31, 44, 45).

How do I select / extract every second value in the vector? Like so: 17, 19, 24, 30, 44

I'm trying to use the seq function: seq(remove, 2) but it doesn't quite work.

Any help is greatly appreciated.

Casease answered 19/11, 2012 at 20:40 Comment(2)
remove[seq(1, length(remove), by = 2)]Sandalwood
The structure for seq is seq(start #, end #, interval). So saying seq(remove,2) is telling R: "start at all the numbers in remove, and count up by the default interval (which is 1) until you get to 2."Micrometeorite
M
162
remove[c(TRUE, FALSE)]

will do the trick.


How it works?

If logical vectors are used for indexing in R, their values are recycled if the index vector is shorter than the vector containing the values.

Here, the vector remove contains ten values. If the index vector c(TRUE, FALSE) is used, the actual command is: remove[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE)]

Hence, all values with odd index numbers are selected.

Matronly answered 19/11, 2012 at 20:59 Comment(2)
Perfectly cromulent R!Vendee
I guess this works only if the vector has an even number of elements, though.Ane
S
27
remove[seq(1,length(remove),2)]
Shulem answered 19/11, 2012 at 20:48 Comment(0)
C
15

Just another alternative:

remove[seq_along(remove) %% 2 > 0]
# [1] 17 19 24 30 44
Casino answered 22/9, 2014 at 21:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.