Select every other element from a vector

RVectorSeq

R Problem Overview


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.

R Solutions


Solution 1 - R

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.

Solution 2 - R

remove[seq(1,length(remove),2)]

Solution 3 - R

Just another alternative:

remove[seq_along(remove) %% 2 > 0]
# [1] 17 19 24 30 44

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1313954View Question on Stackoverflow
Solution 1 - RSven HohensteinView Answer on Stackoverflow
Solution 2 - RGrega KešpretView Answer on Stackoverflow
Solution 3 - RJilber UrbinaView Answer on Stackoverflow