简体   繁体   English

如何比较R中的布尔向量

[英]How to compare boolean vectors in R

I have a vector v and I want to find all those elements, that have values between 4 and 7. v = c(1:9) 我有一个向量v ,我想找到所有那些值在4到7之间的元素.v = c(1:9)

# indices of elements with values larger than 4
which(v > 4)
# indices of elements with values smaller than 7
which(v < 7)

v>4 and v<7 give boolean vectors, which I'd like to combine. v>4v<7给出布尔向量,我想将它们结合起来。 I tried the following, which did not work for me,... 我试过以下,这对我不起作用,......

# combination?
matching = which(v>4 && v<7)  # does not work

How can I applay a boolean operation on two boolean vectors, that gives me a resulting vector? 如何在两个布尔向量上应用布尔运算,这给了我一个结果向量?

Use & and not && . 使用&而不是&& R is different from other languages in that the & is not a bitwise and , but a logical operator. R是从其它语言中的不同在于, &不是按位and ,而是一个逻辑运算符。

&& only evaluates the first element of each vector: &&仅评估每个向量的第一个元素:

'&' and '&&' indicate logical AND and '|' '&'和'&&'表示逻辑AND和'|' and '||' 和'||' indicate logical OR. 表示逻辑OR。 The shorter form performs elementwise comparisons in much the same way as arithmetic operators. 较短的形式以与算术运算符大致相同的方式执行元素比较。 The longer form evaluates left to right examining only the first element of each vector. 较长的形式从左到右评估仅检查每个向量的第一个元素。 Evaluation proceeds only until the result is determined. 评估仅在确定结果之前进行。 The longer form is appropriate for programming control-flow and typically preferred in 'if' clauses. 较长的形式适用于编程控制流程,通常在“if”子句中是首选。

See ?"&&" for more details. 有关详细信息,请参阅?"&&"

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

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