5
$\begingroup$

In R, what is the difference between:

if(x>2 & x<3) ...

and

if(x>2 && x<3) ...

Similarly:

if(x<2 | x>3) ...

and

if(x<2 || x>3) ...
$\endgroup$
10
$\begingroup$

See ?"&": the single version does elementwise comparisons (for when you are doing logical operations on two vectors of the same length, e.g. if in your example x<-c(1.5,3.5). The other one works just like C++'s or java's &&: it only looks at the first element of each vector (this is typically an unexpected downside), but in a typically better performing way: it looks from left to right, and as soon as at least one of the values is false, it knows not to look at the rest anymore.

So if you know, in your examples x<-6 (in any case, just one value), you're better off using &&, otherwise, always use &.

$\endgroup$
1
  • 1
    $\begingroup$ +1; as an addition, it is nice to take a look at any() and all() in this context. $\endgroup$
    – user88
    May 15 '11 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.