0

I am writing a complex if statement in R involving comparing the numeric value of three different number vectors to a given number.

However I don't fully understand the difference between & and &&.

What is the difference between these four:

a[i] > 30 && b[i] > 30 && c[i] > 30
a[i] > 30 & b[i] > 30 & c[i] > 30
a[i] > 30 & b[i] > 30 && c[i] > 30
a[i] > 30 && b[i] > 30 & c[i] > 30

Also I don't fully understand the same situation with | and ||. For instance, what is the difference between:

a[i] > 30 & b[i] > 30 || c[i] > 30

and the following?

a[i] > 30 & b[i] > 30 | c[i] > 30

Any help would be greatly appreciated! My question is about an if statement with three conditions so previous posts haven't fully addressed this.

  • 1
    Since you should probably do this in a vectorized way (not with a loop) you should use `&`. Compare `c(T, T) && c(T, F)` with `c(T, T) & c(T, F)` and read `help("&")`. – Roland Jul 28 '16 at 15:06
  • What about | and ||? I do understand that one compares all elements of a vector while the other only compares the first element, similarly to & and &&, but how does that apply to statements with three conditions where the first condition is linked to the other two by an &? – user3245575 Jul 28 '16 at 15:13
  • @user3245575 There's what is called a shortcut, i.e with X and Y complex expression resulting in TRUE or FALSE and trying: `X && Y` if `X` return FALSE, there's no need to evaluate Y, as the result will be FALSE anyway. Details in 42-'s answer [here](http://stackoverflow.com/a/6559059/3627607) – Tensibai Jul 28 '16 at 15:31
  • And considering your question single and double could be the same here if `a[i]`,`b[i]`and `c[i]` are length 1 vectors (single value). – Tensibai Jul 28 '16 at 15:33
  • The order in which operators are evaluated is described in the `?Syntax ` help page. The `&` and `&&` operators have the same precedence so they are evaluated left to right. The "and" operators have a higher precence than the "or "operators so they are evaulated first. This is similar to `*` and `+` when evaulating `5+2*3`. If you are comparing vectors of length 1 and your statements have no side effects, there is no difference between what `&` and `&&` will return – MrFlick Jul 28 '16 at 15:39

0 Answers0