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

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

Leave a Comment