从向量中选择所有其他元素 [英] Select every other element from a vector
问题描述
假设我有一个向量:
删除 <- c(17, 18, 19, 20, 24, 25, 30, 31, 44, 45)
.
如何选择/提取向量中的每个第二个值?像这样:17, 19, 24, 30, 44
How do I select / extract every second value in the vector? Like so: 17, 19, 24, 30, 44
我正在尝试使用 seq
函数:seq(remove, 2)
但它不太好用.
I'm trying to use the seq
function: seq(remove, 2)
but it doesn't quite work.
非常感谢任何帮助.
推荐答案
remove[c(TRUE, FALSE)]
会解决问题.
它是如何工作的?
如果在 R 中使用逻辑向量进行索引,如果索引向量比包含值的向量短,则它们的值将被回收.
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.
这里,向量 remove
包含十个值.如果使用索引向量c(TRUE, FALSE)
,实际命令为:remove[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE,错误)]
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.
这篇关于从向量中选择所有其他元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!