简体   繁体   中英

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)

# 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. 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.

&& only evaluates the first element of each vector:

'&' and '&&' indicate logical AND and '|' and '||' indicate logical 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.

See ?"&&" for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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