Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the differences between & and &&, | and || in R? [duplicate]

Tags:

r

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.

like image 862
Nick Avatar asked Apr 16 '13 02:04

Nick


1 Answers

Key differences are as below...

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

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

like image 59
Buddha Avatar answered Oct 23 '22 21:10

Buddha