Select every other element from a vector

末鹿安然 提交于 2019-11-26 10:57:34

问题


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.


回答1:


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.




回答2:


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



回答3:


Just another alternative:

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


来源:https://stackoverflow.com/questions/13461829/select-every-other-element-from-a-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!