Why there are four logical operators:
&, &&
|, ||
What's the differences in usage?
Yes, I've checked the docs, yet I'm a little bit confused. The docs says:
‘&’ 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.
I think a piece of example will clearly demonstrate them. Thanks.
Key differences are as below...
Long form(&& or ||) short circuits, which means if it can identify the result by just validating just the first element. While doing &&, if the comparision of first two elements resulted in false, comparing next set of elements will also result in False
. So, it returns false. While doing || if comparision resulted in true in first few elements, we can confidently say that any further validations will not change the result so it returns True
.
Short forms continues to do for the entire vectors and creates a vector of results and returns it.
Hope this helps.
& 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.
Source: http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With