7

Possible Duplicate:
R: subset() logical-and operator for chaining conditions should be & not &&

What is the difference between short (&,|) and long (&&, ||) forms of AND, OR logical operators in R?

For example:

  1. x==0 & y==1
  2. x==0 && y==1
  3. x==0 | y==1
  4. x==0 || y==1

I always use the short forms in my code. Does it have any handicaps?

Community
  • 1
  • 1
Mehper C. Palavuzlar
  • 10,089
  • 23
  • 56
  • 69

1 Answers1

7

& and | - are element-wise and can be used with vector operations, whereas, || and && always generate single TRUE or FALSE

theck the difference:

> x <- 1:5
> y <- 5:1
> (x > 2) & (y < 3) 
  [1] FALSE FALSE FALSE  TRUE  TRUE
> (x > 2) && (y < 3) # here operaand && takes only 1'st elements from logical
                     # vectors (x>2) and (y<3)
> FALSE

So, && and || are commonly used in if (condition) state_1 else state_2 statements, as dealing with vectors of length 1

Max
  • 4,792
  • 4
  • 29
  • 32
  • Perhaps it would be useful to add that ´||´and ´&&´ are prefered in if clauses when only the first value is used. – Luciano Selzer Oct 31 '11 at 12:49
  • 3
    @lselzer ... because `||` and `&&` *short-circuit*, i.e. they don't check subsequent clauses unnecessarily. i.e. `A || B || C` stops evaluating and returns `TRUE` as soon as it finds a `TRUE` element, while `A && B && C` stops evaluating and returns `FALSE` as soon as it finds a `FALSE` element ... this is useful in constructs such as `if (!is.na(x) && x>0)` ... – Ben Bolker Oct 31 '11 at 12:53
  • @Max, a subtle point, but `&&` doesn't always return `TRUE` or `FALSE`. Consider `TRUE && NA`, which returns `NA`. – nograpes Mar 11 '13 at 18:41