我有两个向量,尺寸均为 30000x1,因此只有一列和许多行。第一个向量包含值,第二个向量仅包含 TRUE 或 FALSE。
我想保留向量1的所有行,其中同一行向量2等于TRUE。
我尝试过如下组合:
res=apply(vector1,2,vector2)
res=vector1(vector2)
res=vector1[vector2]
但我无法弄清楚这一点。非常感谢您的帮助。
示例:
vector1:
123
345
667
vector2:
TRUE
FALSE
TRUE
res:
123
667
最佳答案
在 R 中,您可以使用包含 bool 值的相同长度的第二个向量对一个向量进行索引,这样无论第二个向量包含 TRUE,您都可以选择第一个向量的相应元素。
所以你的第三种方法适合我
v1=c(123,345,667)
v2=c(TRUE,FALSE,TRUE)
v1[v2]
输出
[1] 123 667
这是因为 v2
在位置 1 和 3 处包含 TRUE,因此 v1[v2]
相当于 v1[c(1,3)]
.
请参阅point 1 of the introductory documentation关于索引。具体
[indexing with] a logical vector. In this case the index vector must be of the same length as the vector from which elements are to be selected. Values corresponding to TRUE in the index vector are selected and those corresponding to FALSE are omitted
关于r - 当 R 中另一个向量为 TRUE 时,保留向量中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22749606/