简体   繁体   English

当R中的另一个向量为TRUE时,保留向量中的值

[英]Keep values from vector when another vector TRUE in R

I have got two vectors, both with dimensions 30000x1, so only one column and many rows. 我有两个向量,大小均为30000x1,因此只有一列和许多行。 First vector contains values, second only TRUE or FALSE. 第一个向量包含值,第二个仅包含TRUE或FALSE。

I want to keep all the rows of vector1 where at the same row vector2 equals TRUE. 我想保留vector1的所有行,其中同一行中的vector2等于TRUE。

I have tried combinations like: 我尝试过类似的组合:

res=apply(vector1,2,vector2)
res=vector1(vector2)
res=vector1[vector2]

but I can't figure this out. 但我不知道这一点。 Thanks a lot for help. 非常感谢您的帮助。

Example: 例:

vector1:

123
345
667

vector2:
TRUE
FALSE
TRUE

res:
123
667

In R you can index into one vector using a second vector of the same length that contains Boolean values, such that wherever the second vector contains TRUE you select the corresponding element of the first. 在R中,您可以使用包含布尔值的相同长度的第二个向量来索引一个向量,这样,只要第二个向量包含TRUE,您都可以选择第一个向量的对应元素。

So your third way works for me 所以你的第三种方式对我有用

v1=c(123,345,667)
v2=c(TRUE,FALSE,TRUE)
v1[v2]

which outputs 哪个输出

[1] 123 667

This is because v2 contains TRUE at positions 1 and 3, and so v1[v2] is equivalent to v1[c(1,3)] . 这是因为v2在位置1和3处包含TRUE,因此v1[v2]等效于v1[c(1,3)]

See the point 1 of the introductory documentation on indexing. 请参阅索引入门文档第1点 Specifically 特别

[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 选择与索引向量中的TRUE相对应的值,并省略与FALSE相对应的值

This works: 这有效:

 x= 1:3
 y = c(T,F,T)
 x
 #[1] 1 2 3
 y
 #[1]  TRUE FALSE  TRUE
 x[y]
 #[1] 1 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM