Yes I know, there have been a number of questions (see this one, for example) regarding the usage of &
vs. &&
in R, but I have not found one that specifically answers my question.
As I understand the differences,
&
does element-wise, vectorised comparison, much like the other arithmetic operations. It hence returns a logical vector that has length > 1 if both arguments have length > 1.&&
compares the first elements of both vectors and always returns a result of length 1. Moreover, it does short-circuiting:cond1 && cond2 && cond3 && ...
only evaluatescond2
ifcond1
isTRUE
, and so forth. This allows for things likeif(exists("is.R") && is.function(is.R) && is.R())
and particularly means that using&&
is strictly necessary in some cases.
Moreover, if
issues the warning
the condition has length > 1 and only the first element will be used
if its condition has more than one element.
Judging from these preliminaries, I'd consider it safer to prefer &
to &&
in all if
statements where short-circuiting isn't required.
If something went wrong during calculations and I accidentally have a vector in one of &
's arguments, I get a warning, which is good. If not, everything is fine as well.
If, on the other hand, I used &&
, and something went wrong in my calculations and one of &&
's arguments is a vector, I don't get a warning. This is bad. If, for some reason, I really want to compare the first elements of two vectors, I'd argue that it's much cleaner to do so explicitly rather than implicitly.
Note that this is contrary to what seems to be common agreement between R programmers and contrary to what the R docs recommend. (1)
Hence my question: Are there any reasons except short-circuiting that make &&
preferable to &
in if
statements?
(1) Citing help(&&)
:
'&' 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.